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 iterate through it's super classed (A
and B
)? Something like pseudocode:
>>> magicGetSuperClasses(C) (<type 'A'>, <type 'B'>)
One solution seems to be inspect module and getclasstree
function.
def magicGetSuperClasses(cls): return [o[0] for o in inspect.getclasstree([cls]) if type(o[0]) == type]
but is this a "Pythonian" way to achieve the goal?
Python issubclass() is built-in function used to check if a class is a subclass of another class or not. This function returns True if the given class is the subclass of given class else it returns False . Return Type: True if object is subclass of a class, or any element of the tuple, otherwise False.
In general it is necessary. And it's often necessary for it to be the first call in your init. It first calls the init function of the parent class ( dict ).
When you initialize a child class in Python, you can call the super(). __init__() method. This initializes the parent class object into the child class. In addition to this, you can add child-specific information to the child object as well.
The super() function in Python makes class inheritance more manageable and extensible. The function returns a temporary object that allows reference to a parent class by the keyword super. The super() function has two major use cases: To avoid the usage of the super (parent) class explicitly.
C.__bases__
is an array of the super classes, so you could implement your hypothetical function like so:
def magicGetSuperClasses(cls): return cls.__bases__
But I imagine it would be easier to just reference cls.__bases__
directly in most cases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With