Python的新式类与旧式类
2017-06-06 本文已影响0人
FangHao
python的新式类是2.2版本引进来的,我们可以将之前的类叫做经典类或者旧类。为什么要在2.2中引进new style class呢?官方给的解释是:
为了统一类(class)和类型(type)
In [1]: class A():
...: a = 1
...:
In [2]: class B(object):
...: b = 2
...:
In [3]: a = A()
In [4]: b = B()
In [5]: type(a)
Out[5]: instance
In [6]: type(b)
Out[6]: __main__.B
In [7]: a.__class__
Out[7]: <class __main__.A at 0x10ef22668>
In [8]: b.__class__
Out[8]: __main__.B
继承的搜索顺序
继承搜索的顺序发生了改变,经典类多继承属性搜索顺序: 先深入继承树左侧,再返回,开始找右侧;新式类多继承属性搜索顺序: 先水平搜索,然后再向上移动
slots
新式类新增slots属性,可以限制类的属性和方法
In [1]: class Person(object):
...: __slots__ = ('name','age')
...:
In [2]: p = Person()
In [3]: p.name = 'FangHao'
In [4]: p.age = 24
In [5]: p.weigth = 150
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-5-0b75d36f0341> in <module>()
----> 1 p.weigth = 150
AttributeError: 'Person' object has no attribute 'weigth'
pyhton2.x 默认都是旧式类,除非显示的继承object
python3.x 默认都是新式类,隐式的继承object