instance method questions
Peter Otten
__peter__ at web.de
Wed Aug 22 12:19:27 EDT 2007
Danny wrote:
> I have created an instance method for an object using new.instancemethod.
> It works great. Now the questions are:
>
> 1) how do I dynamically inspect an object to determine if it has an
> instance method? (there is a class method with the same name)
Why would you want to do that?
Here is a way that relies on an implementation detail of current CPython:
>>> class Foo(object):
... def foo(self): pass
... def __init__(self):
... import new
... def bar(self): pass
... self.foo = new.instancemethod(bar, self)
...
>>> x = Foo()
>>> x.foo is x.foo
True
>>> del x.foo
>>> x.foo is x.foo
False
This alternative is a little less subtle:
>>> y = Foo()
>>> "foo" in y.__dict__
True
>>> del y.foo
>>> "foo" in y.__dict__
False
Peter
More information about the Python-list
mailing list