繁体   English   中英

如何通过不同文件中的类传递变量值?

[英]How to pass variable value through classes in different files?

我有这个问题。 我需要将在 class A 中的 execute() 方法中处理的“a”变量传递给位于不同文件中 class B 中的 execute() 方法。

在我的代码下方:

文件A.py

a = 0

class A:
    
    def execute(self):
        
        global a
        
        a = 10
        

    

文件B.py

from fileA import A

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

主文件

from fileA import A
from fileB import B

    if __name__== "__main__":
        
        first = A()
        
        first.execute()
        
        second = B()
        
        second.execute()

如果我尝试这个,我会得到一个错误:

AttributeError:类型 object 'A' 没有属性 'a'

我怎样才能使变量“a”的值(在 class A 的方法中详细说明)也可以在 class B 的方法中看到?

提前致谢

你最好这样做:

文件A.py

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

    def execute(self):
        self.a = 10

文件B.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)
        

主文件

from fileA import A
from fileB import B

if __name__== "__main__":

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

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

使用组合。

在 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()

我认为对globalimport存在误解。

import对 2 个不同的事情负责:

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

global仅表示应仅在模块 scope 中搜索引用的变量,并跳过任何本地 scope。

现在会发生什么。

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

fileB 从 fileA 导入 class A ,但不导入模块级变量a 但是它在B.execute方法中使用了一个变量a ,而它从未在模块 scope 和本地模块中声明,因此出现错误。

怎么修:

在最简单的级别,您可以将变量a (您使用的)而不是您不使用的 class A导入到 fileB 模块中:

文件B.py

from fileA import a

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM