【发布时间】:2019-05-08 09:24:54
【问题描述】:
我在使用我的测试模块中的类方法时遇到全局变量问题
示例: 我的测试模块的文本:
cat ./testmodule.py
class testclass(object):
def __init__(self):
self.testfunc()
def testfunc(self):
print(' '.join(globals()).split(' '))
我的测试类的文字相同:
class testclass(object):
def __init__(self):
self.testfunc()
def testfunc(self):
print(' '.join(globals()).split(' '))
我的测试函数的文本,没什么新的:
def testfunc():
print(' '.join(globals()).split(' '))
然后去测试一下。
Python 3.6.6 (default, Aug 13 2018, 18:24:23)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-28)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>>
>>> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa='a'
>>>
>>> import testmodule
>>>
>>> class testclass(object):
... def __init__(self):
... self.testfunc()
...
... def testfunc(self):
... print(' '.join(globals()).split(' '))
...
>>> def testfunc():
... print(' '.join(globals()).split(' '))
一切准备就绪,让我们测试
>>> testfunc()
['__name__', '__doc__', '__package__', '__loader__', '__spec__', '__annotations__', '__builtins__', 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'testmodule', 'testclass', 'testfunc']
变量存在
>>> testclass.testfunc(testclass)
['__name__', '__doc__', '__package__', '__loader__', '__spec__', '__annotations__', '__builtins__', 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'testmodule', 'testclass', 'testfunc']
结果相同,变量存在
>>> testmodule.testclass.testfunc(testclass)
['__name__', '__doc__', '__package__', '__loader__', '__spec__', '__file__', '__cached__', '__builtins__', 'testclass']
>>>
变量丢失。
如何从 testmodule 中获得与 testclass 和 testfunc 相同的结果?
【问题讨论】:
-
Python 没有进程范围的全局变量,只有模块级的全局变量。
-
感谢您的回答!有没有办法在模块函数中使用手动定义的变量?可能不是全局变量而是其他东西?
-
您不想像这样手动创建变量。您的代码如何知道存在哪些变量?
-
你可能会发现将它们全部打包到模块级字典中是最简单的