0

我怎么能称方法'z'?他最好的方法是什么?和一个对象?

文件 test1.py:

from test2 import Test2

class Test1(object):
    def __init__(self):
        pass
    def a(self):
        print("Running a of Test1")
        test_instance2 = Test2()
    def z(self):
        print("Running z of Test1")

if __name__ == '__main__':
    test_instance = Test1()
    test_instance.a()

文件 test2.py:

class Test2:
    def __init__(self):
        self.b()
    def b(self):
        print('Running b of Test2')
        print('Here I want to call method z of Test1') # < How call z in Test1?

运行为:

python test1.py

提前致谢!:) 很抱歉这个基本问题 :$

4

1 回答 1

3

必须传入对Test1实例的引用:

class Test1(object):
    def __init__(self):
        pass
    def a(self):
        print("Running a of Test1")
        test_instance2 = Test2(self)
    def z(self):
        print("Running z of Test1")

class Test2:
    def __init__(self, a):
        self.b(a)
    def b(self, a):
        print('Running b of Test2')
        a.z()

您也可以将a引用存储在Test2实例上:

class Test2:
    def __init__(self, a):
        self.a = a
        self.b()
    def b(self, a):
        print('Running b of Test2')
        self.a.z()
于 2013-11-12T11:56:54.980 回答