调用当前类的类中的调用方法

时间:2013-11-12 11:55:01

标签: python oop

我怎么能调用方法'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

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

1 个答案:

答案 0 :(得分: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()