Python中类之间的通信

时间:2018-01-28 00:12:33

标签: python python-3.x class

我可以从另一个班级调用一个班级,但反之亦然。

TextModeLayout tl = new TextModeLayout(1, 1); Container loginContainer = new Container(tl); TextComponent phone = new TextComponent().label("PHONE").errorMessage("INVALID-PHONE"); CountryCodePicker countryCode = new CountryCodePicker(); phone.getField().setConstraint(TextArea.PHONENUMBER); loginContainer.add(phone); Container loginContainerWithCodePicker = new Container(new BoxLayout(BoxLayout.X_AXIS_NO_GROW)); loginContainerWithCodePicker.add(countryCode).add(loginContainer); // https://stackoverflow.com/questions/8634139/phone-validation-regex String phoneRegEx = "/\\(?([0-9]{3})\\)?([ .-]?)([0-9]{3})\\2([0-9]{4})/"; val.addConstraint(phone, new RegexConstraint(phoneRegEx, "NOT-VALID-NUMBER")); Button loginButton = new Button("LOG-IN"); val.addSubmitButtons(loginButton); (见下文),我可以拨打位于class A的{​​{1}},但是来自Method_B,我无法拨打class B或{ {1}}位于class B

我收到以下错误:

Method_A1

这是我的代码:

test_1.py:

Method_A2

test_2.py:

class A

3 个答案:

答案 0 :(得分:1)

您的导入中有一个循环。尝试添加这样的导入:

class B():

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

这将仅在定义后从test_1导入A

答案 1 :(得分:1)

要在脚本之间进行通信,您需要将test_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)

答案 2 :(得分:1)

调用A

时,您可以将类Method_B作为参数传递

test_1.py:

from test_2 import *

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

    ...

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