Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

self.__class__.__bases__ doesn't trace back to class object

Tags:

python

class

Perhaps this is a trivial question. under python, how come self.__class__.__bases__ doesn't trace back to object? Mine only shows a tuple of the one single parent above the class.

like image 608
lucas Avatar asked Feb 08 '26 00:02

lucas


2 Answers

self.__class__.__bases__ only goes "one level up" in class inheritance. If you want to trace all the way through every parent class up to object, use self.__class__.__mro__.

like image 115
sinback Avatar answered Feb 12 '26 05:02

sinback


__bases__essentially contains the base-classes passed to the metaclass constructor.

So a class definition statement like:

class Foo(Bar, Baz):
    pass

Is essentially equivalent to:

Foo = type("Foo", (Bar, Baz), {})

So the __bases__ attribute is essentially the value to the bases argument of the type constructor: type(object_or_name, bases, dict)

If you want the entire inheritance chain, you should use:

self.__class__.mro()

To read a little bit more about the internals of class creating, read about metaclasses, section 3.3.3.1 to 3.3.3.6

like image 43
juanpa.arrivillaga Avatar answered Feb 12 '26 04:02

juanpa.arrivillaga