【问题标题】:How to pass variable value through classes in different files?如何通过不同文件中的类传递变量值?
【发布时间】: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


【解决方案1】:

你最好这样做:

文件A.py

class A():
    def __init__(self, a=0):
        self.a = a

    def execute(self):
        self.a = 10

fileB.py

class B():
    def __init__(self, class_a, b=0):
        self.class_a = class_a
        self.b = b

    def execute(self):
        self.b = self.class_a.a
        print(self.b)
        

main.py

from fileA import A
from fileB import B

if __name__== "__main__":

    first = A()
        
    first.execute()
        
    second = B(first)
        
    second.execute()

您可以跳过 self.aself.b 的初始化部分,但最好保留它

【讨论】:

    【解决方案2】:

    使用组合。

    在module_a中:

    class A:
        a = 0
    
        def set_a(self):
            self.a = 10
    

    在module_b中:

    from module_a import A
    
    class B:
        a = A()
    
        def execute(self):
            print(a.a)
    
    if __name__ == "__main__":
        b = B()
        b.a.set_a()
        b.execute()
    

    【讨论】:

      【解决方案3】:

      我认为对globalimport存在误解。

      import 负责两件事:

      • 模块被加载到sys.modules列表中并被执行
      • 标识符在当前范围内可用

      global 只表示只在模块范围内搜索引用的变量,并跳过任何本地范围。

      现在会发生什么。

      fileA 声明了一个类 (A) 和一个变量 (a)。而A 类只包含一个execute 方法,没有其他属性。 A.execute恰好设置了模块级a变量的值。

      fileB 从 fileA 导入类 A,但不导入模块级变量 a。但是它在B.execute方法中使用了一个变量a,而它既没有在模块范围内也没有在本地范围内声明过,因此出现了错误。

      如何解决:

      在最简单的层面上,您可以将变量 a(您使用的)导入到 fileB 模块中,而不是您不使用的类 A

      fileB.py

      from fileA import a
      
      class B:
          
          def execute(self):
              
              b = a
              
              print (b)
          
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-11
        • 2020-06-06
        • 1970-01-01
        • 1970-01-01
        • 2020-10-26
        相关资源
        最近更新 更多