Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get list of bases in an object

How do you get a list of all the bases utilized by an object in it's creation? For instance:

class MixinA(object):
    pass

class MixinB(object):
    pass

class mixedClass(MixinB, MixinA, object):
    pass

my_object = mixedClass()
bases_used = my_object.???   # Is there a property that contains a list of [MixinA, MixinB, object]?

I'm looking to somehow extract what the bases of an object are, primarily because I'm actually building the object's class dynamically but I want to report on what mixins were used in certain error cases.

like image 730
Nathaniel Ford Avatar asked Nov 20 '25 22:11

Nathaniel Ford


2 Answers

You can get the bases from the __class__

bases_used = my_object.__class__.__bases__

print(bases_used)
(<class '__main__.MixinB'>, <class '__main__.MixinA'>, <type 'object'>)
like image 166
Padraic Cunningham Avatar answered Nov 22 '25 10:11

Padraic Cunningham


see inspect.getmro, or inspect.getclasstree:

>>> inspect.getmro(type(my_object))
(<class '__main__.mixedClass'>, <class '__main__.MixinB'>, <class '__main__.MixinA'>, <class 'object'>)

alternatively, __bases__

>>> type(my_object).__bases__
(<class '__main__.MixinB'>, <class '__main__.MixinA'>, <class 'object'>)
like image 35
behzad.nouri Avatar answered Nov 22 '25 10:11

behzad.nouri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!