Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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?

like image 751
Anthony Towns Avatar asked Nov 05 '09 22:11

Anthony Towns


Video Answer


1 Answers

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.

like image 116
Robert Rossney Avatar answered Nov 10 '22 09:11

Robert Rossney