Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python super class reflection

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?

like image 888
jelovirt Avatar asked Aug 25 '08 09:08

jelovirt


People also ask

How do you check super class in Python?

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.

Is super () necessary Python?

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 ).

What does super () __ Init__ do in Python?

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.

How does super () work in Python?

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.


1 Answers

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.

like image 164
John Avatar answered Sep 22 '22 23:09

John