Python 的new style class

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

参考

Python new style class

转载于:https://www.cnblogs.com/tony-wong/p/4895837.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值