对于python3无区别
对于python3.x 在定义类时,有没有写继承object已经没有区别了,因为python3会自动继承object
对于python2有区别
在python 2.x中,继承object的类叫新式类,不继承object的类叫经典类。
那在python 2.x中写object和不写object有什么区别呢?下面用代码来理解它们的区别。
区别1
class Person:
pass
class Person2(object):
pass
if __name__ == "__main__":
x = Person()
print "Person", dir(x)
y = Person2()
print "Person2", dir(y)
运行结果
Person ['__doc__', '__module__']
Person2 ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__',
'__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']
- 不继承object的类,只有 ['__doc__', '__module__']
- 继承object类,有['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__',
'__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__'] 有更多对象可操作,这些都是类中的高级特性,对于那些高手来说,这些特性比较有用。 - 无论是否继承object,都是属于object对象,print isinstance(A, object), 结果都为true
区别2
#经典类
class A:
def __init__(self):
print 'this is A'
def save(self):
print 'come from A'
class B(A):
def __init__(self):
print 'this is B'
class C(A):
def __init__(self):
print 'this is C'
def save(self):
print 'come from C'
class D(B,C):
def __init__(self):
print 'this is D'
d1=D()
d1.save() #结果为'come from A
经典类中使用的是A的save方法
#新式类
class A(object):
def __init__(self):
print 'this is A'
def save(self):
print 'come from A'
class B(A):
def __init__(self):
print 'this is B'
class C(A):
def __init__(self):
print 'this is C'
def save(self):
print 'come from C'
class D(B,C):
def __init__(self):
print 'this is D'
d1=D()
d1.save() #结果为'come from C'
新式类中使用的是C的save方法
在经典类中 搜索按深度优先 路径B->A->C, 执行A中save
在新式类的 搜索按广度优先 路径B->C->A, 执行C中save
python 多重继承的方法解析顺序
class A:
def say(self):
print("A Hello:", self)
class B(A):
def eat(self):
print("B Eating:", self)
class C(A):
def eat(self):
print("C Eating:", self)
class D(B, C):
def say(self):
super().say()
print("D Hello:", self)
def dinner(self):
self.say()
super().say()
self.eat()
super().eat()
C.eat(self)
Python 能区分 d.eat() 调用的是哪个方法, 是因为 Python 会按照特定的顺序遍历继承图,python3就是广度优先。 这个顺序叫方法解析顺序( Method Resolution Order, MRO)。 类都有一个名为 __mro__ 的属性, 它的值是一个元组, 按照方法解析顺序列出各个超类, 从当前类一直向上, 直到object 类。
D 类的 __mro__ 属性如下 :
>>> D.__mro__
(<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>)