Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does defining a class in Python 2.7, without inheriting an object, not result in a __mro__ method? [duplicate]

Tags:

python

I am working on Mac OS X v10.10 (Yosemite) with Python 2.7.9.

Here is what I have tried:

  1. Define a class

    class A:
        def test(self):
            print "test"
    

    Then run

    A.__mro__
    

    Then I got

    >>> A.__mro__
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: class A has no attribute '__mro__'
    
  2. Then I define

    class B(object):
        def test(self):
            print "test"
    

    Then run

    B.__mro__
    

    Then I got

    >>> B.__mro__
    (<class '__main__.B'>, <type 'object'>)
    

What is the different between the two definitions?

I found that in Python 3, the edition without "object" still has the __mro__ method.

like image 562
Da Tong Avatar asked Mar 10 '15 15:03

Da Tong


People also ask

What is __ MRO __ in Python?

The Method Resolution Order (MRO) is the set of rules that construct the linearization. In the Python literature, the idiom "the MRO of C" is also used as a synonymous for the linearization of the class C.

Do Python classes need to inherit from object?

Inheritance is a required feature of every object oriented programming language. This means that Python supports inheritance, and as you'll see later, it's one of the few languages that supports multiple inheritance.

What is __ new __ in Python?

In the base class object , the __new__ method is defined as a static method which requires to pass a parameter cls . cls represents the class that is needed to be instantiated, and the compiler automatically provides this parameter at the time of instantiation.

What is __ bases __ in Python?

Python provides a __bases__ attribute on each class that can be used to obtain a list of classes the given class inherits. The __bases__ property of the class contains a list of all the base classes that the given class inherits.


1 Answers

__mro__ is only defined for new-style classes. In Python 2, a class is only new-style if it inherits from object (or from a built in type, which in turn inherits from object), while all classes in Python 3 are new-style no matter what.

like image 186
jwodder Avatar answered Oct 21 '22 07:10

jwodder