Python 2.6: Determining if a method is inherited
Fuzzyman
fuzzyman at gmail.com
Mon Oct 6 09:00:25 EDT 2008
On Oct 6, 7:16 am, Christian Heimes <li... at cheimes.de> wrote:
> Terry Reedy wrote:
> > In 3.0, the test returns true because function attributes only get
> > wrapped when bound. In the meanwhile, " 'object' in repr(X.__lt__)"
> > should do it for you.
>
> This session should give you some hints how to archive your goal :)
> Have fun!
>
> >>> import types
> >>> class A(object):
> ... def __lt__(self):
> ... pass
> ...
> >>> isinstance(A.__lt__, types.MethodType)
> True
> >>> isinstance(A.__gt__, types.MethodType)
> False
>
> >>> type(A.__lt__)
> <type 'instancemethod'>
> >>> type(A.__gt__)
> <type 'method-wrapper'>
> >>> type(A.__str__)
> <type 'wrapper_descriptor'>
> >>> type(A.__new__)
> <type 'builtin_function_or_method'>
>
> >>> A.__lt__.im_func
> <function __lt__ at 0x7f03f9298500>
> >>> A.__lt__.im_func == A.__lt__.im_func
> True
> >>> A.__gt__.im_func
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> AttributeError: 'method-wrapper' object has no attribute 'im_func'
However - I need to detect whether a method is inherited from
*object*. All those differences you have shown behave identically if
the class inherits from 'int'.
I am trying to detect explicit implementation of comparison methods -
so there is a big difference between inheriting from int and
inheriting from object (meaningful comparison methods existing on one
and not the other).
What I went for in the end:
import sys as _sys
if _sys.version_info[0] == 3:
def _has_method(cls, name):
for B in cls.__mro__:
if B is object:
continue
if name in B.__dict__:
return True
return False
else:
def _has_method(cls, name):
for B in cls.mro():
if B is object:
continue
if name in B.__dict__:
return True
return False
See this page for why I needed it:
http://www.voidspace.org.uk/python/weblog/arch_d7_2008_10_04.shtml#e1018
Michael
--
http://www.ironpythoninaction.com/
More information about the Python-list
mailing list