I am working on Mac OS X v10.10 (Yosemite) with Python 2.7.9.
Here is what I have tried:
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__'
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.
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.
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.
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.
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.
__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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With