开发者

retrieve inheritance relationship information in python

Say I have the following inheritance relationship.

object-&开发者_运维技巧gt;Car->SUV

object is the father of Car and Car is the father of the SUV.

How can I use Python programs to get such relationship information,like use dir to get the attributes of a class


Use __bases__:

In [11]: SUV.__bases__
Out[11]: (<class '__main__.Car'>,)

In [12]: Car.__bases__
Out[12]: (<type 'object'>,)

If the purpose is to call the parent method from a child method, use super() instead.


In addition to __bases__ which aix mentioned, there is also __mro__ which will tell you all the classes you're inheriting from, back to object, and the order in which they will be searched for a given attribute.

class foo(object):
   pass

class bar(foo):
   pass

print bar.__mro__
>>> (<class '__main__.bar'>, <class '__main__.foo'>, <type 'object'>)

If you have an instance, rather than a class, you can do type(x).__mro__.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜