Dynamically removing methods in new-style classes

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Wed Sep 12 13:17:56 EDT 2007


On Wed, 12 Sep 2007 14:28:15 +0000, agupta0318 wrote:

> I am trying unsuccessfully to remove some methods from an instance,
> based on values passed in to the constructor as in the following
> example:

[snip]


>>> class C(object):
...     def method(self):
...             return "method exists"
...
>>> c = C()
>>> c.method()
'method exists'
>>> del c.__class__.method
>>> c.method()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'C' object has no attribute 'method'


Of course deleting methods from the class has the disadvantage that you 
delete them from the class. A better solution might be to mask them:


>>> class C(object):
...     def method(self):
...             return "method exists"
...     def methodgone(self, *args):
...             raise AttributeError("method gone")
...
>>> c = C()
>>> d = C()
>>> c.method = c.methodgone
>>> c.method()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in methodgone
AttributeError: method gone
>>> d.method()
'method exists'


-- 
Steven.



More information about the Python-list mailing list