内置常量#
名称 None,False,True 和 __debug__ 无法重新赋值(赋值给它们,即使是属性名,将引发 SyntaxError),所以它们可以被认为是“真正的”常量。
演示如下:
False = 'e'
Cell In[1], line 1
False = 'e'
^
SyntaxError: cannot assign to False
True = 5
Cell In[2], line 1
True = 5
^
SyntaxError: cannot assign to True
None = 'w'
Cell In[3], line 1
None = 'w'
^
SyntaxError: cannot assign to None
__debug__ = 2
Cell In[4], line 1
__debug__ = 2
^
SyntaxError: cannot assign to __debug__
NotImplemented#
NotImplemented 是 types.NotImplementedType 类型的唯一实例。
type(NotImplemented)
NotImplementedType
作为布尔值来解读 NotImplemented 已被弃用。虽然它目前会被解读为真值,但将同时发出 : DeprecationWarning。它将在未来的 Python 版本中引发 TypeError。
bool(NotImplemented)
/tmp/ipykernel_3849/3586968809.py:1: DeprecationWarning: NotImplemented should not be used in a boolean context
bool(NotImplemented)
True
当二元(或就地)运算返回 NotImplemented 时,解释器将尝试对另一种类型(或其他一些回滚操作,取决于运算符)实施反射操作。如果所有尝试都返回 NotImplemented,则解释器将引发适当的异常。错误返回的 NotImplemented 将导致误导性错误消息或返回到 Python 代码中的 NotImplemented 值。
from demo.a import A, B
a = A(4)
b = B(4)
a == b
False
b == a
False