嗨,我是python编程的新手。请在python3中帮助我解决此问题:
pack.py
class one:
def test(self):
number = 100 ######I want to access this value and how?
print('test')
class two:
def sample(self):
print('sample')
另一个
from pack import *
class three:
def four(self):
obj = one()
print(obj.test())
###### I want to access the number value in this file and i don't know how #######
obj = three()
obj.four()
number
需要在全局范围内,这意味着在函数定义之外(不应该缩进)如果变量在函数中,则无法在另一个文件中获取它
pack.py
另一个
或者,如果您正在使用类:
pack.py
另一个
这里有一个替代方案 pack.py
另一个
按照您的方法,您使用类来访问变量。最好在构造函数中实例化变量(init类One中的方法)。然后导入该类并在另一个文件的另一个类中访问它
此外,以大写字母开头命名类也是一种很好的做法。有更多可能的方法,但希望能有所帮助
相关问题 更多 >
编程相关推荐