Python中元组中的value-asignments是如何工作的?

2024-04-19 12:31:59 发布

您现在位置:Python中文网/ 问答频道 /正文

在用Python编写脚本时,我遇到了sys模块sys.flags的这个内置方法部分,它返回用于运行Python脚本的标志元组。输出如下所示:

(debug=0, inspect=0, interactive=0, optimize=1, dont_write_bytecode=0, no_user_site=0, no_site=0, ignore_environment=0, verbose=0, bytes_warning=0, quiet=0, hash_randomization=1, isolated=0, dev_mode=False, utf8_mode=0)

我很困惑,因为我以为你不能在Python的另一个表达式中嵌入赋值,到目前为止,我还没有在Google上找到解释这个元组行为的答案。你知道吗


Tags: 模块方法nodebug脚本mode标志sys
3条回答

实际输出为:

>>> sys.flags
sys.flags(debug=0, inspect=0, interactive=0, optimize=0, dont_write_bytecode=0, no_user_site=0, no_site=0, ignore_environment=0, verbose=0, bytes_warning=0, quiet=0, hash_randomization=1, isolated=0, dev_mode=False, utf8_mode=0)

开头括号前的sys.flags是至关重要的。它表明sys.flags不是元组。你知道吗

然而,您完全可以创建一个类,它的__repr__方法将返回这种类似元组的表示:

class Weird:
    def __init__(self, a, b):
        self.a, self.b = a, b

    def __repr__(self):
        return f"(a={self.a}, b={self.b})"

然后输出将如下所示:

>>> Weird(1,2)
(a=1, b=2)

但是Weird绝对不是元组。你知道吗

实际上,做:

isinstance(sys.flags, tuple)

将返回True。但那是因为^{}^{},它继承自tuple类型。从文档中:

The term “named tuple” applies to any type or class that inherits from tuple and whose indexable elements are also accessible using named attributes.

输出不显示tuple

>>> import sys
>>> sys.flags
sys.flags(debug=0, inspect=0, interactive=0, optimize=0, dont_write_bytecode=0, no_user_site=0, no_site=0, ignore_environment=0, verbose=0, bytes_warning=0, quiet=0, hash_randomization=1, isolated=0, dev_mode=False, utf8_mode=0)
>>> type(sys.flags)
<class 'sys.flags'>

元组如下所示:

>>> tuple(sys.flags)
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, False, 0)

它实际上返回具有自定义表示的类的实例。你知道吗

请注意,这是“数据类”的典型表示。它显示了如何创建或可以创建这样的对象。例如namedtuple具有类似的表示(不是意外,因为^{} is a ^{}!)地址:

>>> from collections import namedtuple
>>> Person = namedtuple('Person', 'name, age')
>>> Person(20, 'me')
Person(name=20, age='me')
>>> Person(name=20, age='me')
Person(name=20, age='me')

相关问题 更多 >