【发布时间】:2021-08-01 18:29:19
【问题描述】:
我有这个问题。 我需要传递一个在 A 类的 execute() 方法中处理的“a”变量 到位于不同文件中的类 B 中的 execute() 方法。
在我的代码下面:
文件A.py
a = 0
class A:
def execute(self):
global a
a = 10
fileB.py
from fileA import A
class B:
def execute(self):
b = a
print (b)
main.py
from fileA import A
from fileB import B
if __name__== "__main__":
first = A()
first.execute()
second = B()
second.execute()
如果我尝试这个,我会得到一个错误:
AttributeError: type object 'A' has no attribute 'a'
我怎样才能使变量“a”的值(在 A 类的方法中详细说明)也可以在 B 类的方法中看到?
提前致谢
【问题讨论】:
-
我建议阅读“依赖注入”(或IoC)。它不仅可以解决您的问题,还可以帮助您提高编程技能!
-
一般来说,方法之间的通信方式是将数据作为参数传入并返回数据。
标签: python class variables scope global