python - LGB 范围规则和在 Python 中使用 "self"

标签 python

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/

相关文章:

python - 如何使用 OpenCV 获得金属光泽物体的轮廓

python - 在 jupyter 中使用 matplotlib 绘制非常小的值

导入 tensorflow 1.7 时 Python 内核死机

python - 如何在 Vim 中注释掉一段 Python 代码

python - 添加 super 用户时 Django SYNCDB 失败(Windows 7、mySQL、Django 1.2.4、mySQL 5.5)

python - 如何将项目附加到 python 列表中的列表?

python - 字计数器(编程导论2(python))

python - 具有多列的 GtkTreeView 和具有单一自定义类型的 GtkListStore(在 Python 中)

python - Kafka producer.send 从不发送消息

python - MysqlDB调用类型错误: 'int' object is not iterable python