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 when they're not in a suitable state, so that I get something like:
>>> wiz=Wizard()
>>> dir(wiz)
['__doc__', '__module__', 'addmana']
>>> wiz.addmana()
>>> dir(wiz)
['__doc__', '__module__', 'addmana', 'domagic']
>>> wiz.domagic()
>>> dir(wiz)
['__doc__', '__module__', 'addmana']
>>> wiz.domagic()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: Wizard instance has no attribute 'domagic'
I can see how to add methods (types.MethodType(method, object)), but I can't see any way to delete a method for just a single object:
>>> wiz.domagic
<bound method Wizard.domagic of <__main__.Wizard instance at 0x7f0390d06950>>
>>> del wiz.domagic
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: Wizard instance has no attribute 'domagic'
Overriding __dir__ (and getting an InvalidState or NotEnoughMana exception on invocation instead of AttributeError on reference) might be okay, but I can't see how to mimic the built-in behaviour of dir() accurately. (Ideally I'd prefer a way that works in Python 2.5, too)
Ideas?
You can't delete a class method from an instance of that class because the instance doesn't have that method. The protocol is: if o
is an instance of class Foo
, and I call o.bar()
, first o
is examined to see if it has a method named bar
. If it doesn't, then Foo
is examined. The methods aren't bound to the instance unless they override its class.
I don't see any good that can come from the road that you're going down here, either.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With