为什么python 2.7定义没有继承对象的类会不会有__mro__方法?

Da *_*ong 10 python

我正在使用python 2.7.9在Mac OS X Yosemite上工作.

这是我尝试过的:

  1. 定义一个类

    class A:
        def test(self):
            print "test"
    
    Run Code Online (Sandbox Code Playgroud)

    然后运行

    A.__mro__
    
    Run Code Online (Sandbox Code Playgroud)

    然后我得到了

    >>> A.__mro__
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: class A has no attribute '__mro__'
    
    Run Code Online (Sandbox Code Playgroud)
  2. 然后我定义

    class B(object):
        def test(self):
            print "test"
    
    Run Code Online (Sandbox Code Playgroud)

    然后运行

    B.__mro__
    
    Run Code Online (Sandbox Code Playgroud)

    然后我得到了

    >>> B.__mro__
    (<class '__main__.B'>, <type 'object'>)
    
    Run Code Online (Sandbox Code Playgroud)

这两个定义有什么不同?我发现在python 3中,没有"对象"的版本仍然有__mro__方法.

jwo*_*der 6

__mro__仅为新样式类定义。在Python 2中,如果类继承自object(或从内置类型继承object,而内置类型又继承自),则该类只是新样式,而Python 3中的所有类都是新样式。