首页 > 解决方案 > 不同类之间的联系

问题描述

请考虑以下代码:

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 类的一个方法,假设这不会导致无限循环(如上面的示例所示)。

在这种情况下,我想在 B 类的 print_b() 触发时调用 print_warning_a(),并且我想在 A 类的 print_a() 触发时调用 print_warning_b()。

如何修改代码来实现这一点?

谢谢你。

标签: python

解决方案


您需要以某种方式连接 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类(或引用两个类),这是不可避免的。


推荐阅读