【问题标题】:Python globals var different inside class when imported导入时,Python全局变量在类内部不同
【发布时间】:2012-12-05 07:26:18
【问题描述】:

这显然是某种范围或导入问题,但我无法弄清楚。比如:

classes.py

class Thing(object):

    @property
    def global_test(self):
        return the_global

然后……

test.py

from classes import Thing

global the_global
the_global = 'foobar'

t = Thing()
t.global_test

:(

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "classes.py", line 4, in global_test
    return the_global
NameError: global name 'the_global' is not defined

任何帮助都会很棒!

【问题讨论】:

    标签: python class scope global-variables


    【解决方案1】:

    Python 中的“global”是模块内顶层可访问的变量。

    这条消息:

    NameError: global name 'the_global' is not defined
    

    classes.py 中引发意味着您的classes.py 文件中没有名为the_global 的全局变量。

    Python 模块不共享全局变量。 (嗯,不是你希望他们分享的方式)

    【讨论】:

      【解决方案2】:

      “全局”变量仅在模块范围内将变量定义为全局变量 它在哪里使用。您不能在此处使用“全局”来访问模块外的变量 “类”模块的范围。

      如果您必须处理全局定义,这里的正确解决方案是:移动“全局” 变量到专用模块并使用适当的导入语句导入变量 进入你的“类”模块。

      myvars.py:

      MY_GLOBAL_VAR = 42
      

      classes.py:

      import myvars
      
      class Thing():
      
         def method(self):
             return myvars.MY_GLOBAL_VAR # if you need such a weird pattern for whatever reason
      

      【讨论】:

      • 谢谢,“奇怪”的模式当然是为了演示。
      猜你喜欢
      • 1970-01-01
      • 2022-08-02
      • 2019-07-24
      • 1970-01-01
      • 1970-01-01
      • 2015-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多