问题描述
我意识到还有其他线程可以解决这个问题,但是由于我对'Classes'还是很陌生,并且已经构造了我的类结构...我想找到一种可以集成到我的代码中的方法.我敢肯定,这将不是一个难回答的问题!
I realize there are other threads addressing this problem but as I am fairly new to 'Classes' and have already constructed my class structure ... I would like to find a method that I can integrate into my code. I'm sure this will NOT be a difficult one to answer!
第一个文件:NameResult.py
from NameAssign import *
NameList = NameWorks()
print(NameList.InputNames(NameVar))
第二个文件:NameAssign.py
class NameWorks:
def __init__(self, NameVar = []):
self.NameVar = NameVar
def InputNames(self, NameVar):
global NameVar
NameVar = ['harry', 'betty', 'sam']
结果:
NameError: name 'NameVar' is not defined
非常感谢所有回复...
All replies are much appreciated ...
推荐答案
NameVar
在NameAssign
中未定义;它仅作为局部变量存在于NameAssign.NameWorks.InputNames()
中.解决此问题的最简单方法是在全局级别的NameAssign
中对其进行定义.
NameVar
is not defined in NameAssign
; it only exists within NameAssign.NameWorks.InputNames()
as a local variable. The easiest way to fix this is to define it in NameAssign
at the global level.
事实证明,这就是您想要做的:
It turns out that this is what you want to do:
import NameAssign
namelist = NameAssign.NameWorks(['harry', 'betty', 'sam'])
print namelist.InputNames() # or print(...) for Py3k
NameAssign.py
class NameWorks(object):
def __init__(self, names):
self.names = names
def InputNames(self):
return self.names
这篇关于Python跨模块变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!