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中,是对象在内存中的地址)。
参考
- Python的内建常量
- Python的常量
- python的内建函数
- Python 的内建函数
- Python 的内建对象
- python的内建函数
- Python的常量与变量
- Python的内建sort方法
- Python 有用的内建函数
- Python中常用的内建函数
- Python的一些内建函数1
- Python的一些内建函数2
- Python的一些内建函数3
- Python 几个常用的内建函数
- Python的一些内建函数4
- Python的一些内建函数5
- Python字符串类型的内建函数
- python中常用的内建函数
- 解决appt.exe finished with non- zero exit value 1问题
- 深入Java单例模式
- 【SDUTOJ 3307】 a (第k小背包)
- 基于android平台的视觉检测智能相机的实现-opencv4android的应用
- Ipython
- Python的内建常量
- sql server 2012 报表开发(1) 如何使用Reporting Service 2012制作报表
- ajax传参给php,php连接服务器数据库并返回数据过程详解
- Swift学习 PlayGround初探
- LeetCode_Remove Duplicates from Sorted Array
- 给TextView添加滚动条
- URL Scheme
- 【SDUTOJ 3314】 l (扩欧裸题)
- PAT 1080. Graduate Admission (30)