[经典类与新式类](https://www.jianshu.com/p/2ZxRsn)
[Python2和Python3中新式类、经典类(旧式类)的区别](https://www.jianshu.com/p/6f9d99f7ad54)
[Python新式类与经典类的区别](https://www.cnblogs.com/blackmatrix/p/5630515.html)
经典类:不由任意内置类型派生出的类
新式类:由任意内置类型派生出的类(只要一个内置类型位于类树的某个位置)
python2.1:只有经典类
python2.2:引入新式类
python3:取消经典类,默认继承`object`
~~~
# >= Python 2.2
class Person(object):pass # 新式类写法
class Person():pass # 经典类写法
class Person:pass # 经典类写法
~~~
~~~
# Python3.*:
class Person(object):pass# 推荐
class Person():pass
class Person:pass
~~~
区别
-----
#### 1. 如果经典类被作为父类,子类调用父类的构造函数时会出错
~~~
#基类(经典类)
class Person:
def __init__(self):
print "Hi, I am a person. "
#子类
class Student(Person):
def __init__(self):
super(self.__class__, self).__init__()
if __name__ == "__main__":
student = Student()
#出错啦!TypeError: must be type, not classobj
~~~
新式类作为父类就可以:
~~~
#基类(新式类)
class Person(object):
def __init__(self):
print "Hi, I am a person."
#子类
class Student(Person):
def __init__(self):
super(self.__class__, self).__init__()
if __name__ == "__main__":
student = Student()
~~~
#### 2. MRO继承顺序的区别(见后续章节)
#### 3. 类实例类型的区别
经典类中:所有类都是`'classobj'`,所有的实例都是`'instance'`,不利于不同实例的对比/判断。
新式类:所有的类都是`'type'`,每个实例的type()各不相同,能够看出实例化的来源。
~~~
# 经典类:
# python2.7.5
class A(): pass
class B(): pass
a = A()
b = B()
print(type(A))#
print(type(B))#
print(type(a))#
print(type(b))#
print(type(a) == type(b))# True
~~~
~~~
# 新式类:
# python2.7.5
class A(object): pass
class B(object): pass
a = A()
b = B()
print(type(A))#
print(type(B))#
print(type(a))#
print(type(b))#
print(type(a) == type(b))# False
~~~