python魔法变量之__class__,__bases__,__mro__

bases:一个类的基类

In [4]: class B:
   ...:     pass
   ...: 

In [5]: class A(B):
   ...:     pass
   ...: 

In [6]: A.__bases__
Out[6]: (<class __main__.B at 0x7fdafd3f89a8>,)

class:实例所对应的类(仅新式类中)

In [12]: class T(object): #新式类
    ...:     pass
    ...: 

In [13]: t = T()

In [14]: type(t)
Out[14]: __main__.T

In [15]: t.__class__
Out[15]: __main__.T

In [21]: type(t) is t.__class__
Out[21]: True

In [29]: T.__class__
Out[29]: type

In [30]: T.__bases__
Out[30]: (object,)

In [31]: t.__bases__
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-28-92db851817a5> in <module>()
----> 1 t.__bases__

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


In [16]: class T1: # 旧式类,type(t)为instance,而新式类为class
    ...:     pass
    ...: 

In [17]: t = T1()

In [18]: type(t)
Out[18]: instance

In [24]: type(t) is  t.__class__
Out[24]: False


In [44]: class Base(object):
...: pass
...:

In [45]: class A(Base):
...: pass
...:

In [46]: A.__class__
Out[46]: type

In [47]: A.__mro__ #返回值一个元素为class元组,相当于js的原型链,在方法解析时会用到(作为查找路径)
Out[47]: (__main__.A, __main__.Base, object)

In [48]: Base.__subclasses__() #子类
Out[48]: [__main__.A]