元组作为单例的实际使用

Practical use of tuple as a singleton

data models 的文档中,它提到了使用单个项目元组作为单例的可能性,因为它是不可变的。

Tuples

A tuple of one item (a ‘singleton’) can be formed by affixing a comma to an expression...

据我在Python中的理解,单例的功能类似于常量。它是一个固定值,保持相同的内存地址,以便您可以测试相等性或同一性。例如,NoneTrueFalse 都是内置单例。

然而,考虑到这种用法,使用这种方式定义的元组对于笨拙的语法来说似乎不切实际:

HELLO_WORLD = ("Hello world",)
print HELLO_WORLD
> ('Hello world',)
print HELLO_WORLD[0]
> Hello world

更不用说,如果你记得索引它,它只能作为单例使用。

HELLO_WORLD[0] = "Goodbye world"

Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    HELLO_WORLD[0] = "Goodbye world"
TypeError: 'str' object does not support item assignment

意味着您可以轻松做到这一点:

HELLO_WORLD = "Goodbye world"
print HELLO_WORLD
> Goodbye world

考虑到这些限制,这个单例实现有什么意义吗?我看到的唯一优点是创建起来很简单。我见过的其他方法是更复杂的方法(使用 类 等)但是我没有想到还有其他用途吗?

我认为这对实现单例根本没有用,它没有添加任何东西:元组仍然可以被新的单元素元组覆盖。无论如何,在您的示例中,您的值是一个字符串,它本身已经是不可变的。

但我认为您提到的文档行 ("A tuple of one item (a ‘singleton’)") 根本没有提到 单例模式,而是数学用法词的,见Wikipedia on Singleton (mathematics)

The term is also used for a 1-tuple (a sequence with one element).