Python 设置 class,float 和 int 求值
Python set class, float and int evaluation
我还没有看到 set Class
的实现细节,但我想答案就在某处。 Python 赋值基本上评估右值并使用标识符作为引用对象以指向 class 对象。集合也是如此,即它们是一个抽象数据结构或一个 'collection' 的引用对象。集合不允许重复,当我像这样创建集合时:
s1 = {False, 1.0, 1, "a"} > {False, 1.0, "a"}
Float class 胜过 int class,显然他们评估的是同一件事。但为什么 float 显示而 init 不显示?我似乎找不到合适的答案或在源代码中看到它。
顺便提一下,我注意到如果使用 .union() 操作,True 和 False 将以某种方式分别取代 1 和 0。所以看起来 Floats 战胜了 Ints,Ints 战胜了 Bools。但是,
>>> s1 = {False, 'a', 1}
>>> s2 = {True, 'a', 0}
>>> s1 | s2
{False, 1, 'a'}
False remains.. 我不知道这是否是一个 REPL 问题但是在再次测试之后我每次都得到 {0, 1, 'a'}
我不知道是什么发生了。
>>> s1 = {True, 'a', 1}
>>> s1
{1, 'a'}
>>> s2 = {False, 'a', 0}
>>> s2
{0, 'a'}
我错过了什么?
>>> s1.union(s2)
{0, 1, 'a'}
来自https://docs.python.org/3/reference/datamodel.html#the-standard-type-hierarchy:
The Boolean type is a subtype of the integer type, and Boolean values behave like the values 0 and 1, respectively, in almost all contexts, the exception being that when converted to a string, the strings "False" or "True" are returned, respectively.
我还没有看到 set Class
的实现细节,但我想答案就在某处。 Python 赋值基本上评估右值并使用标识符作为引用对象以指向 class 对象。集合也是如此,即它们是一个抽象数据结构或一个 'collection' 的引用对象。集合不允许重复,当我像这样创建集合时:
s1 = {False, 1.0, 1, "a"} > {False, 1.0, "a"}
Float class 胜过 int class,显然他们评估的是同一件事。但为什么 float 显示而 init 不显示?我似乎找不到合适的答案或在源代码中看到它。
顺便提一下,我注意到如果使用 .union() 操作,True 和 False 将以某种方式分别取代 1 和 0。所以看起来 Floats 战胜了 Ints,Ints 战胜了 Bools。但是,
>>> s1 = {False, 'a', 1}
>>> s2 = {True, 'a', 0}
>>> s1 | s2
{False, 1, 'a'}
False remains.. 我不知道这是否是一个 REPL 问题但是在再次测试之后我每次都得到 {0, 1, 'a'}
我不知道是什么发生了。
>>> s1 = {True, 'a', 1}
>>> s1
{1, 'a'}
>>> s2 = {False, 'a', 0}
>>> s2
{0, 'a'}
我错过了什么?
>>> s1.union(s2)
{0, 1, 'a'}
来自https://docs.python.org/3/reference/datamodel.html#the-standard-type-hierarchy:
The Boolean type is a subtype of the integer type, and Boolean values behave like the values 0 and 1, respectively, in almost all contexts, the exception being that when converted to a string, the strings "False" or "True" are returned, respectively.