Custom Search

Wednesday, December 15, 2010

python django how find all base classes of a class or object

python django how find base classes of a class

# Using __bases__ and inspect.getmro()

class A:
def __init__(self):
pass

class B(object):
def __init__(self):
pass

class C(A,B):
def __init__(self):
pass

class D(C):
def __init__(self):
pass

c1 = C()
d1 = D()

print "\n--------C.__base__---------", C.__base__
print "\n--------C.__bases__---------", C.__bases__
import inspect
print "\n--------inspect.getmro(C)------", inspect.getmro(C)
print "\n--------C.mro------", C.mro()

print "\n============================="

print "\n--------D.__bases__---------", D.__bases__
print "\n--------inspect.getmro(D)------", inspect.getmro(D)

print "\n============================="

print "\n-------d1.__class__----------", d1.__class__
print "\n-------d1.__class__.__base__----------", d1.__class__.__base__
print "\n-------d1.__class__.__bases__----------", d1.__class__.__bases__
print "\n-------d1.__class__.__base__.__subclasses__()----------",
d1.__class__.__base__.__subclasses__()


OUTPUT
======

# python aa.py

--------C.__base__--------- class '__main__.B'>

--------C.__bases__--------- (class __main__.A at 0x7f78c2434ad0>, class '__main__.B'>)

--------inspect.getmro(C)------ (class '__main__.C'>, class __main__.A at 0x7f78c2434ad0>,
class '__main__.B'>, type 'object'>)

--------C.mro------ [class '__main__.C'>, class __main__.A at 0x7f78c2434ad0>,
class '__main__.B'>, type 'object'>]

=============================

--------D.__bases__--------- (class '__main__.C'>,)

--------inspect.getmro(D)------ (class '__main__.D'>, class '__main__.C'>,
class __main__.A at 0x7f78c2434ad0>, class '__main__.B'>, type 'object'>)

=============================

-------d1.__class__---------- class '__main__.D'>

-------d1.__class__.__base__---------- class '__main__.C'>

-------d1.__class__.__bases__---------- (class '__main__.C'>,)

-------d1.__class__.__base__.__subclasses__()---------- [class '__main__.D'>]

More...
More...


No comments:

Post a Comment