Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class Inheritance in Python

I'm new to python and trying to get a list of the classes an object's class inherits from. I'm trying to do this using the bases attribute but I'm not having any success. Can someone please help me out?

def foo(C):
     print(list(C.__bases__))

class Thing(object):
    def f(self):
        print("Yo")

class Shape(Thing):
    def l(self):
        print("ain't no thang")

class Circle(Shape):
    def n(self):
        print("ain't no shape")

test = Circle()
foo(test)
like image 328
Alex Winchell Avatar asked Sep 25 '12 02:09

Alex Winchell


People also ask

What is class inheritance in Python?

Inheritance allows us to define a class that inherits all the methods and properties from another class. Parent class is the class being inherited from, also called base class. Child class is the class that inherits from another class, also called derived class.

What is class inheritance example?

OOP is all about real-world objects and inheritance is a way of representing real-world relationships. Here's an example – car, bus, bike – all of these come under a broader category called Vehicle. That means they've inherited the properties of class vehicles i.e all are used for transportation.

What is meant by class inheritance?

Class inheritance is a mechanism for using the interface and implementation of one or more classes as the basis for another class. The inheriting class, also known as a subclass, inherits from one or more classes, known as superclasses.

What is class inheritance in OOP?

Inheritance in OOP = When a class derives from another class. The child class will inherit all the public and protected properties and methods from the parent class. In addition, it can have its own properties and methods. An inherited class is defined by using the extends keyword.


2 Answers

Only classes have __bases__; class instances do not. You can get the class object through an instance's __class__: use foo(test.__class__) or foo(Circle).

like image 187
nneonneo Avatar answered Sep 27 '22 21:09

nneonneo


Use inspect, from documentation

Return a tuple of class cls’s base classes, including cls, in method resolution order. No class appears more than once in this tuple. Note that the method resolution order depends on cls’s type. Unless a very peculiar user-defined metatype is in use, cls will be the first element of the tuple.

>>> import inspect
>>> inspect.getmro(test.__class__)
(<class '__main__.Circle'>, <class '__main__.Shape'>, <class '__main__.Thing'>, <type 'object'>)
>>> 

This traverses up the inheritance hierarchy & prints all classes, including object. Pretty Cool eh ?

like image 43
Srikar Appalaraju Avatar answered Sep 27 '22 22:09

Srikar Appalaraju