不同类之间的联系

时间:2019-05-13 09:51:42

标签: python

请考虑以下代码:

class A:
    a = "a"

    def print_a(self):
        print("A says:", self.a)

    def print_warning_a(self):
        print("A says:", "Warning! B wrote something!")


class B:
    b = "b"

    def print_a(self):
        print("B says:", self.b)

    def print_warning_b(self):
        print("B says:", "Warning! A wrote something!") 

if __name__=="__main__":    
    class_a = A()
    class_b = B()

    class_a.print_a()
    class_b.print_b()

我希望输出为:

>> A says: a
>> B says: Warning! A wrote something!
>> B says: b
>> A says: Warning! B wrote something!

换句话说:我有两个课程(A和B)。每当要调用类B的另一个方法时,我都想调用类A的方法。另外,我想每次调用A类的另一个方法时都调用B类的方法,假设这不会导致无限循环(如上例所示)。

在这种情况下,我想打电话给     print_warning_a() 什么时候     print_b() B类火灾,我也想打电话     print_warning_b() 什么时候     print_a() A级火灾。

如何修改代码以实现此目的?

谢谢。

1 个答案:

答案 0 :(得分:1)

您需要以某种方式连接A和B。事件系统是替代方法,但如果只是学习活动,我们可以做一些简单的事情。例如,通过相互保存对另一个类的引用,如下所示:

class A:
    def __init__(self):
        self.a = "a"
    def set_other(self, other):
        self.other = other
    def print_a(self):
        print("A says:", self.a)
        self.other.print_warning()
    def print_warning(self):
        print("A says:", "Warning! B wrote something!")

class B:
    def __init__(self):
        self.b = "b"
    def set_other(self, other):
        self.other = other
    def print_b(self):
        print("B says:", self.b)
        self.other.print_warning()
    def print_warning(self):
        print("B says:", "Warning! A wrote something!")

if __name__=="__main__":
    class_a = A()
    class_b = B()
    class_a.set_other(class_b)
    class_b.set_other(class_a)
    class_a.print_a()
    class_b.print_b()

在创建实例后,我必须设置引用 ,因为我们具有循环依赖关系。还要注意在类self.a = "a"中声明类的正确方法:__init__()。它按预期工作:

A says: a
B says: Warning! A wrote something!
B says: b
A says: Warning! B wrote something!

请注意,对other引用的调用已封装在方法内部,因此不应将other.other.other之类的调用暴露给外界。最后,必须在某个地方有对other类的引用(或对两个类的引用),这是不可避免的。