delete a methode of a object?

Erik Max Francis max at alcyone.com
Wed Oct 9 03:57:14 EDT 2002


Thomas Marek wrote:

> is it possible to delete a method of a object?

For a typical instance of a class, not in a direct way that's
instance-specific.  For your standard instance of a class, the method is
not in the instance's dictionary, it's in the dictionary of the class:

>>> class C:
...  def f(self, x):
...   print x
... 
>>> c = C()
>>> c.f(2)
2
>>> del c.f # the method isn't in the instance
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: C instance has no attribute 'f'
>>> del C.f # it's here in the class
>>> c.f(2)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: C instance has no attribute 'f'

But that would affect all other instances.  If you want
instance-specific removal of methods, the most obvious solution to me is
simply attaching a callable attribute that raises an AttributeError:

>>> def duh(x): raise AttributeError          
... 
>>> c.f = duh
>>> c.f(2)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 1, in duh
AttributeError

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/  \ My heart is pure as the driven slush.
\__/ Tallulah Bankhead
    HardScience.info / http://www.hardscience.info/
 The best hard science Web sites that the Web has to offer.



More information about the Python-list mailing list