Python class inheritance

I am new to python and trying to get a list of classes inherited by an object class. I am trying to do this using an attribute bases, but I have no success. Can someone please help me?

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)
+5
source share
4 answers

Only classes have __bases__; there is no class. You can get a class object through an instance __class__: use foo(test.__class__)or foo(Circle).

+6
source

Use inspect, from the documentation

clss , cls, . . clss. , cls .

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

, object. , ?

+4
print '\n'.join(base.__name__ for base in test.__class__.__bases__)

Or using the module inspect:

from inspect import getmro
print '\n'.join(base.__name__ for base in getmro(test))
+2
source

Your work is in progress foo. But you need to pass a class foo, not an instance.

In [1]: def foo(C):
   ...:          print(list(C.__bases__))
   ...:

In [2]: class Thing(object):
   ...:         def f(self):
   ...:                 print("Yo")
   ...:

In [3]: class Shape(Thing):
   ...:         def l(self):
   ...:                 print("ain't no thang")
   ...:

In [4]: class Circle(Shape):
   ...:         def n(self):
   ...:                 print("ain't no shape")
   ...:

In [5]: test = Circle()

In [6]: foo(test)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-6-7b85deb1beaa> in <module>()
----> 1 foo(test)

<ipython-input-1-acd1789d43a9> in foo(C)
      1 def foo(C):
----> 2          print(list(C.__bases__))
      3

AttributeError: 'Circle' object has no attribute '__bases__'

In [7]: foo(Thing)
[<type 'object'>]

In [8]: foo(Circle)
[<class '__main__.Shape'>]

In [9]: foo(Shape)
[<class '__main__.Thing'>]
+1
source

All Articles