Skip to main content
 首页 » 编程设计

python之Python 元组中的赋值如何工作

2025年05月04日13mfryf

在使用 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 上找到解释这个元组行为的答案。

请您参考如下方法:

实际输出为:

>>> 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 绝对不是一个元组。