If I have Python code
class A():
pass
class B():
pass
class C(A, B):
pass
and I have class C
, is there a way to iterat
@John: Your snippet doesn't work -- you are returning the class of the base classes (which are also known as metaclasses). You really just want cls.__bases__
:
class A: pass
class B: pass
class C(A, B): pass
c = C() # Instance
assert C.__bases__ == (A, B) # Works
assert c.__class__.__bases__ == (A, B) # Works
def magicGetSuperClasses(clz):
return tuple([base.__class__ for base in clz.__bases__])
assert magicGetSuperClasses(C) == (A, B) # Fails
Also, if you're using Python 2.4+ you can use generator expressions instead of creating a list (via []), then turning it into a tuple (via tuple
). For example:
def get_base_metaclasses(cls):
"""Returns the metaclass of all the base classes of cls."""
return tuple(base.__class__ for base in clz.__bases__)
That's a somewhat confusing example, but genexps are generally easy and cool. :)