1.新式类
1.1 新式类的引入
新式类(new style class)是python2.2引入的新特性,在面向对象的语言中,class是与语言的内建(build-in)类型相对应的自定义类型。但是在Python的世界里,在新式类出现之前,事情不是这样的:
clsas C:
pass
x = C()
print x.__class__
print type(x)
其输出为:
__main__.A
<type 'instance'>
对象x是由class A生成,但是其类型却不是A,而是‘instance’,不仅如此,在新式类出现之前,所有的对象,其类型均是instance,python官方对其的解释是:
Up to Python 2.1 the concept of class was unrelated to the concept of type, and old-style classes were the only flavor available. For an old-style class, the statement x.__class__ provides the class of x, but type(x) is always <type 'instance'>. This reflects the fact that all old-style instances, independent of their class, are implemented with a single built-in type, called instance.
在python2.2中,为了统一class与type的概念,引入了新式类,与之相对应的class成为旧式类(old style class)或者经典类(classic class)
1.2 新式类的概念
先看定义,从新式类派生的类为新式类。这是一个在逻辑上有点问题的定义,它已经不是鸡生蛋还是蛋生鸡的问题了,已经变成了鸡生鸡的问题了。从新式类派生的类为新式类,那么作为父类的新式类从哪里来?Python 为了解决这个问题引入了一个特殊的类,object,它有一个牛逼闪闪的名字“top-level type”,如果你不知道新式类从哪里来,就从它这里来,从object派生的类,就是新式类。我们再来看对象的类型
class C(object):
pass
x = C()
print x.__class__
print type(x)
其输出为:
<class '__main__.A'>
<class '__main__.A'>
现在,对象x由class A生成,其类型也不再是instance,而变成class A
1.3 新式类的作用(待补充):
子类化内置类型
引入装修器
enable computed properties