Python的内建常量

来源:互联网 发布:java 内存泄露几种情况 编辑:程序博客网 时间:2024/06/05 19:47

内建的6个常量是(参考)

'True', 'False', 'None', 'Ellipsis', '__debug__', 'NotImplemented'

True和False是bool的实例
None是NoneType的唯一实例

__debug__

This constant is true if Python was not started with an -O option. O表示optimization的意思。
这个和assert语句有关,assert语句等价于:

if __debug__:    if not expression: raise AssertionError

if __debug__:    if not expression1: raise AssertionError(expression2)

参考

Note
None, False, True and __debug__不能再被赋值(assignments to them, even as an attribute name, raise SyntaxError)。

Ellipsis

Ellipsis是ellipsis的实例(不过我没找到ellipsis定义于哪),代码中的…会自动变成Ellipsis,这有个例子(参考):

# 等差数列构造器class ProgressionMaker(object):    def __getitem__(self, key):        if isinstance(key, tuple) and len(key) == 4 and key[2] is Ellipsis:            return range(key[0], key[-1] + 1, key[1] - key[0])maker = ProgressionMaker()print(list(maker[1, 3, ..., 9]))

NotImplemented

NotImplemented是个特殊值,它能被二元特殊方法返回(比如__eq__() 、 __lt__() 、 __add__() 、 __rsub__() 等),表明某个类型没有像其他类型那样实现这些操作。同样,它或许会被原地处理(in place)的二元特殊方法返回(比如__imul__()、__iand__()等)。还有,它的bool值为True。
一个例子可以说明NotImplemented的用法:

class A(object):    def __init__(self, value):        self.value = value    def __eq__(self, other):        if isinstance(other, A):            print('Comparing an A with an A')            return other.value == self.value        if isinstance(other, B):            print('Comparing an A with a B')            return other.value == self.value        print('Could not compare A with the other class')        return NotImplementedclass B(object):    def __init__(self, value):        self.value = value    def __eq__(self, other):        if isinstance(other, B):            print('Comparing a B with another B')            return other.value == self.value        print('Could not compare B with the other class')        return NotImplementeda=A(2)b=B(2)print(b==a)

输出是:
Could not compare B with the other class
Comparing an A with a B
True

在Python中,a == b会调用a.__eq__(b)。
B的__eq__()并没有实现B与A的比较,b.__eq__(a)方法返回NotImplemented,这样会导致调用A中的__eq__()方法。而且由于在A中的__eq__()定义了A和B之间的比较,所以就得到了正确的结果(True)。
如果A中的__eq__()也返回NotImplemented,那么运行时会退化到使用内置的比较行为,即比较对象的标识符(在CPython中,是对象在内存中的地址)。

参考

0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 手机上q币充错了怎么办 q币数值充错了怎么办 微信充值商户电话是假了怎么办 微信冲话费冲错了怎么办 淘宝退款不退邮费怎么办 淘金币买的退款怎么办 淘宝退款不退运费怎么办 拼多多不退运费怎么办 开发商不退团购服务费怎么办 支付宝话费充错了怎么办 电视版本低不支持投屏怎么办 绝地求生刺激战场不支持机型怎么办 手机不支持微信运动怎么办 淘宝虚拟商品买家退货退款怎么办 虚拟品申请啦退货退款怎么办 淘宝充值话费没到账怎么办 淘宝全球购买到假货怎么办 车跑路上没油了怎么办 摩托车跑路上没油了怎么办 话费充了不到帐怎么办 网上代充被骗了怎么办 天猫买东西没积分怎么办 购物时不要天猫积分怎么办 618没有天猫积分怎么办 话费充错了号码怎么办? 微信被骗充话费怎么办 微信话费充多了怎么办 睫毛烫的太卷了怎么办 烫完睫毛太卷了怎么办 烫睫毛太卷了怎么办 用微信充话费充错了怎么办 微信给空号充话费了怎么办 微信充话费充错号码是空号怎么办 淘宝充流量不到账怎么办 微信退货不退款怎么办 京东话费交错号怎么办? 微信缴费错了怎么办 给手机充话费被退款怎么办 买到假货淘宝商家已关店怎么办 手机刷错系统了怎么办 苹果手机成砖了怎么办