python 中 None 之外的其他唯一实例对象?

Other unique-instance objects besides None in python?

python 语言参考提到了三个具有单个唯一实例的对象:NoneNotImplementedEllipsissection 3.2 "The Standard Type Hierarchy"). The test x is None is a common idiom made possible by the guaranteed uniqueness of None. I cannot find any other mention of unique-instance objects, either in python documentation or on stack overflow. A few questions, like this one 具有有趣的关于构造此类对象的方法的建议,但我想知道的是除了这三个内置函数之外是否还有我遗漏的。

例如,() 似乎是唯一的(在 CPython 中公认的非常有限的测试中),那么测试 x is () 安全吗?或者在这种情况下 x == () 是强制性的吗?

值得一提的是,() 在 PyPy 4.0.1 中不是唯一的:

>>>> x = ()
>>>> x is ()
False

好吧...您可以将任何全局对象视为 "unique",因为它始终是同一个对象。

例如:

>>> x = file
>>> x is file
True
>>> x = True
>>> x is True
True
>>> x = ZeroDivisionError
>>> x is ZeroDivisionError
True

没有什么特别之处:

>>> x = None
>>> x is None
True

您可能想知道为什么您应该测试 x is None 而不是 x == None

答案是:x == None 将调用 x.__eq__(None),这可能 return Truex 实际上不是 [=19] 的各种情况下=](虽然在现实中这并不常见)。

实例?

嗯,你可能会说有区别:None是一个实例。

嗯,事实是,Python 中的一切都是对象,这意味着一切都是实例。在我的示例中,fileZeroDivisionErrortype 的实例,Truebool 的实例,而 None 是 [=27= 的实例](注意 typetype 的一个实例,因此规则没有例外)。

关于 None 有一件特别的事情 - 它是 NoneType 的唯一实例并且你不能创建其他实例(除非有一些好技巧?)

但这实际上是 NoneType 的 属性 - 它不允许您创建新实例:

TypeError: cannot create 'NoneType' instances

但这对整个故事来说并不是真正重要的。

EDIT 这些“唯一实例对象”被称为单例。当然,你也可以自己做一些。

不,没有其他具有单值的内置类型。这些单例的唯一亲戚是 bool 类型,它允许两个值(即 TrueFalse)*.

Python 2.x 中(我在 3.x 中找不到它们)您可以通过从 types[=51 中导入 NotImplementedType, EllipsisType, NoneType 来查看此限制=] 模块并意识到它显然不是花哨的自定义 TypeError:

In [13]: from types import NoneType

In [14]: n = NoneType()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-14-b386f51143fb> in <module>()
----> 1 n = NoneType()

TypeError: cannot create 'NoneType' instances
不幸的是,

() 不是唯一的,它代表一个空元组,如果类型 TupleNoneType 是唯一的意义上是唯一的,那么它的所有实例都需要具有相同值.


如果您想仔细查看这些,它们分别位于 Objects/object.c in lines 1351 and 1473NoneNotImplemented。省略号尚未找到。


*更新:根据PEP 285 - Adding a bool type[=51,TrueFalse显然是也是单例=]:

The values False and True will be singletons, like None. Because the type has two values, perhaps these should be called "doubletons"? The real implementation will not allow other instances of bool to be created