Given a class Foo
(whether it is a new-style class or not), how do you generate all the base classes - anywhere in the inheritance hierarchy - it issubclass
of?
views:
411answers:
4
+6
A:
inspect.getclasstree()
will create a nested list of classes and their bases.
Ned Batchelder
2009-09-09 19:47:54
+5
A:
See the __bases__
property available on a python class
, which contains a tuple of the bases classes:
>>> def classlookup(cls):
... c = list(cls.__bases__)
... for base in c:
... c.extend(classlookup(base))
... return c
...
>>> class A: pass
...
>>> class B(A): pass
...
>>> class C(object, B): pass
...
>>> classlookup(C)
[<type 'object'>, <class __main__.B at 0x00AB7300>, <class __main__.A at 0x00A6D630>]
Crescent Fresh
2009-09-09 19:48:12
This may introduce duplicates. And this is why the documentation for `getmro` explicitly says "No class appears more than once in this tuple"?
Sridhar Ratnakumar
2009-09-09 20:45:25
+4
A:
inspect.getmro(cls)
works for both new and old style classes and returns the same as NewClass.mro()
: a list of the class and all its base classes.
>>> class A(object):
>>> pass
>>>
>>> class B(A):
>>> pass
>>>
>>> import inspect
>>> inspect.getmro(B)
(<class '__main__.B'>, <class '__main__.A'>, <type 'object'>)
THC4k
2009-09-09 20:28:21
Well done: http://docs.python.org/library/inspect.html#inspect.getmro
Sridhar Ratnakumar
2009-09-09 20:44:22