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 类的一个方法,假设这不会导致无限循环(如上面的示例所示)。
在这种情况下,我想在 B 类的 print_b() 触发时调用 print_warning_a(),并且我想在 A 类的 print_a() 触发时调用 print_warning_b()。
如何修改代码来实现这一点?
谢谢你。
解决方案
您需要以某种方式连接 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
类(或引用两个类),这是不可避免的。
推荐阅读
- c# - 更改只读数组的值
- java - 如何发送带有存储在 s3 存储桶中的附件文件的 ses 原始电子邮件
- excel - 在某些情况下如何合并/合并日期(年份)
- javascript - NextJS 中的多个布局或条件 css 导入
- awk - 如何从一个文件中 grep 数据,进行小操作,然后将它们附加到另一个文件中
- flutter - Flutter:忽略图标的空间
- docker - 使用 docker 多阶段构建强制目标参数?
- c# - C# ASP.NET Core - 返回 T 类型属性的通用方法
- c# - html 敏捷返回难以理解的文本
- javascript - 将数组映射到引导 4 轮播滑块,但将数据获取到单个滑块