Python中普通变量访问有什么用?

2024-04-20 08:59:03 发布

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

在python中,这种语法被接受并正确运行

foo = "test variable"
foo # plain variable access
foo # plain variable access
print(foo)
>>>>test variable    

问:我的问题是,在Python的上下文中,用例是什么?其他一些语言会强调这是一个语法错误。你知道吗


为了确保发生了一些事情,我使用了dis模块并得到了以下输出

def test():
    foo = "test variable"
    foo
    return foo

dis.dis(test)
>>>>3           0 LOAD_CONST               1 ('test variable')
                2 STORE_FAST               0 (foo)

    4           4 LOAD_FAST                0 (foo)
                6 POP_TOP

    5          12 LOAD_FAST                0 (foo)
              14 RETURN_VALUE

def test():
    foo = "test variable"
    return foo

dis.dis(test)
>>>>9           0 LOAD_CONST               1 ('test variable')
                2 STORE_FAST               0 (foo)

   10           4 LOAD_FAST                0 (foo)
                6 RETURN_VALUE

正如你所看到的,有一个额外的操作,我似乎不明白。你知道吗

 4 LOAD_FAST                0 (foo)
 6 POP_TOP

Tags: storetestreturnaccessfootopdefload
2条回答

除了REPL作为print(repr(var) if var is not None else '')的快捷方式外,没有其他用途:

>>> x = 3
>>> x
3

LOAD_FAST将变量添加到堆栈中,然后POP_TOP将其删除。实际上什么都没发生。你知道吗


为什么这是允许的?因为这很简单。我的意思是我们必须小心地允许func()而不是func。当我们使用属性时,它也变得更加复杂,例如:

class T:
    def __init__(self):
         self.gets = 0
    @property
    def attr(self):
        self.gets += 1

t = T()
print(t.gets)  # 0
t.attr
print(t.gets)  # 1

因此,即使引用“普通属性”的行为也可能产生副作用。你知道吗

额外的foo没有可观察到的影响。dis输出显示值被加载,然后立即被丢弃。你知道吗

在python中丢弃值不是错误。你知道吗

相关问题 更多 >