str2 = "Global"
class InClass:
str2 = "Class"
def Set(self, msg):
self.str2 = msg
def Print(self):
print(str2)
g = InClass()
g.Set("Instance")
g.Print()
如果我运行这段代码,我会得到“Global”作为结果。但我不明白为什么。
通过调用实例 g 的 Set() 方法,变量 str2 现在位于实例 g 的命名空间中。然后,遵循 LGB 作用域规则,实例 g 的命名空间是第一个可以找到 str2 的命名空间!所以,结果应该是“Instance”。
这是错的吗?
最佳答案
这不是它的工作原理。 print(str2)
从方法内部访问全局 str2
。要访问 str2
成员,请使用 print(self.str2)
。
阅读此 SO question and answers了解全部详情。摘录from there :
At any time during execution, there are at least three nested scopes whose namespaces are directly accessible: the innermost scope, which is searched first, contains the local names; the namespaces of any enclosing functions, which are searched starting with the nearest enclosing scope; the middle scope, searched next, contains the current module's global names; and the outermost scope (searched last) is the namespace containing built-in names.
这不包括类成员,因此您必须使用 self
显式引用它们。
关于python - LGB 范围规则和在 Python 中使用 "self",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4085231/