在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
除了REPL作为
print(repr(var) if var is not None else '')
的快捷方式外,没有其他用途:LOAD_FAST
将变量添加到堆栈中,然后POP_TOP
将其删除。实际上什么都没发生。你知道吗为什么这是允许的?因为这很简单。我的意思是我们必须小心地允许
func()
而不是func
。当我们使用属性时,它也变得更加复杂,例如:因此,即使引用“普通属性”的行为也可能产生副作用。你知道吗
额外的
foo
没有可观察到的影响。dis输出显示值被加载,然后立即被丢弃。你知道吗在python中丢弃值不是错误。你知道吗
相关问题 更多 >
编程相关推荐