繁体   English   中英

Python: Function scope 在 class 内

[英]Python: Function scope inside a class

让我们考虑下面的代码。

name = "John"

class MyClass:
    name = "Tom"
    list_1 = [name] * 2
    list_2 = [name for i in range(2)]

乍一看,人们可能期望list_1list_2都具有相同的内容: ["Tom", "Tom"] ,但事实并非如此。 list_1计算结果为["Tom", "Tom"] ,而list_2计算结果为["John", "John"]

I read that when a function is nested inside a class, Python will use variables defined in the module scope and not in the class scope. list_1 is not a function, so it uses name from the class scope, whereas list_2 is a function and, therefore, uses name from the module scope. 我知道这就是它的工作原理,但这似乎违反直觉。 我不明白原因。

使用列表推导确定范围需要一些时间来适应。 在这种情况下,列表理解list2 = [name for i in range(2)]中的本地 scope 暂时阻止 class 本地 scope。 见: 这个答案

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM