Is it possible to delete a method from an object (not class) in python?

前端 未结 8 1752
借酒劲吻你
借酒劲吻你 2020-12-31 13:24

I have a class with a few methods, some of which are only valid when the object is in a particular state. I would like to have the methods simply not be bound to the objects

8条回答
  •  情歌与酒
    2020-12-31 13:56

    If an object is in a state where calling a given method on that object doesn't make sense, having it disappear from the object's interface seems like the wrong way to handle the problem. More explicit error handling gives you the ability to explain the problem more precisely to your callers, throwing NotEnoughMana instead of presenting them with a method-not-found error.

    If you're worried about having a bunch of function prefixes that look like this:

    if self.StateNotValid():
        raise NotEnoughMana()
    

    ...then you could use a decorator on each function. It's shorter, and gives you an easy way to grep for all special-state-requiring functions.

提交回复
热议问题