Python中类间的通信

2024-04-25 21:45:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我可以从另一个类调用一个类,但不能从另一个类调用。你知道吗

class A(见下文),我可以调用位于class BMethod_B,但是从class B,我不能调用位于Method_A1Method_A2。你知道吗

我得到以下错误:

NameError: name 'A' is not defined

这是我的密码:

测试1.py:

from test_2 import *

class A():

    def __init__(self):

        self.key = 1
        self.call_Method_B = B().Method_B(self.key)

    def Method_A1(self):
        print("Method_A1: ok")

    def Method_A2(self):
        print("Method_A2: ok")

if __name__ == '__main__':

    start_A = A()

测试2.py:

class B():

    def Method_B(self,key):
        self.key = key

        if self.key ==1:
            self.call_Method_A1 = A().Method_A1()
        else:
            self.call_Method_A2 = A().Method_A2()

Tags: keynamepyselfa2ifdefa1
3条回答

要在脚本之间进行通信,需要将test\u 1作为一个模块导入:

from test_1 import * 

A的调用方式改为:

if self.key ==1:
    self.call_Method_A1 = A.Method_A1(self)
else:
    self.call_Method_A2 = A.Method_A2(self)

你的导入中有一个循环。尝试添加如下导入:

class B():

    def Method_B(self,key):
        from test_1 import A
        ....

只有在定义了A之后,才会从test\u1导入它。你知道吗

调用Method_B时,可以将类A作为参数传递

测试1.py:

from test_2 import *

class A():
    def __init__(self):
        self.key = 1
        self.call_Method_B = B().Method_B(self.key, A)

    ...

测试2.py:

class B():

    def Method_B(self, key, A):
        ...

一种更为传统的方式是:

# test_1.py

from test_2 import B

class A():

    def __init__(self):
        self.key = 1
        self.b = B(self)
        self.b.method_b(self.key)

    @staticmethod
    def method_a1():
        print("Method_A1: ok")

    @staticmethod
    def method_a2():
        print("Method_A2: ok")


if __name__ == '__main__':
    start_a = A()



# test_2.py

class B():

    def __init__(self, instance_of_a):
        self.a = instance_of_a

    def method_b(self, key):
        self.key = key

        if self.key == 1:
            self.a.method_a1()
        else:
            self.a.method_a2()

相关问题 更多 >