0

これは明らかに何らかのスコープまたはインポートの問題ですが、私にはわかりません。何かのようなもの:

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

どんな助けでも素晴らしいでしょう!

4

2 に答える 2

3

"global" in Python is a variable accessible in top level within module.

This message:

NameError: global name 'the_global' is not defined

raised within classes.py means you do not have a global named the_global within your classes.py file.

Python modules do not share global variables. (well, not in the way you want them to share)

于 2012-12-18T05:53:12.407 に答える
0

The 'global' variables only defines a variable as global inside the scope of the module where it is used. You can not use 'global' here to access a variable outside the module scope of the 'classes' module.

The proper solution here if you have to deal with global defines or so: move the "global" variables into a dedicated module and use a proper import statement to import the variables into your 'classes' module.

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
于 2012-12-18T05:52:41.320 に答える