1.

How can we check if a certain class is a subclass of another?

Answer»

Python offers more than one way to CHECK if a certain class is inherited from the other. In Python each class is a subclass of object class. This can be verified by running built-in issubclass() function on class A as follows:

>>> class A: pass >>> issubclass(A,object) True

We now CREATE B class that is inherited from A. The issubclass() function returns true for A as well as object class.

>>> class B(A): pass >>> issubclass(B,A) True >>> issubclass(B,object) True

You can also use __bases__ attribute of a class to find out its super class.

>>> A.__bases__ (<class 'object'>,) >>> B.__bases__ (<class '__main__.A'>,)

FINALLY the mro() method returns method resolution ORDER of methods in an inherited class. In our case B is inherited from A, which in turn is a subclass of object class.

>>> B.mro() [<class '__main__.B'>, <class '__main__.A'>, <class 'object'>]


Discussion

No Comment Found