python - 如何实现具有多个 init 继承的 super()?
问题描述
我正在做一个涉及多重继承的练习,这些初始化器需要多个参数,并且我想,super() 如何解决这个问题,而不是手动调用每个超类?
class One:
def __init__(self, address, phone):
self.address = address
self.phone = phone
class Two:
def __init__(self, city):
self.city = city
class Three(One,Two):
def __init__(self, country, address, phone, city):
self.country = country
One.__init__(self, address, phone)
Two.__init__(self, city)
print(f"{address}, " + f"{phone}, " + f"{self.city}, " + f"{self.country}")
i = Three("Acountry", "AnAddress", "Aphone", "Acity")
这很好用,所有的参数都打印得很好,但我不知道如何在super()
这里实现。
我尝试在子类上添加 2 个超级:
super().__init__(address, phone)
super().__init__(city)
甚至在父类上添加一个 super() 以使其指向class Two
:
class One:
def __init__(self, address, phone, city):
self.address = address
self.phone = phone
super().__init__(city)
class Two:
def __init__(self, city):
self.city = city
class Three(One,Two):
def __init__(self, country, address, phone, city):
self.country = country
super().__init__(address, phone)
print(f"{address}, " + f"{phone}, " + f"{self.city}, " + f"{self.country}")
i = Three("Acountry", "AnAddress", "Aphone", "Acity")
它不起作用。
我如何super()
在有效的原始代码中实现?
解决方案
您应该阅读Raymond Hettinger 的这篇文章,其中介绍了如何super
设计工作,并概述了使用它的类的外观。他建议将参数作为关键字参数传递,并super().__init__
在 every 结束时调用__init__
:
class One:
def __init__(self, address, phone, **kwargs):
self.address = address
self.phone = phone
super().__init__(**kwargs)
class Two:
def __init__(self, city, **kwargs):
self.city = city
super().__init__(**kwargs)
class Three(One,Two):
def __init__(self, country, address, phone, city, **kwargs):
self.country = country
super().__init__(address=address, phone=phone, city=city, **kwargs)
print(f"{address}, " + f"{phone}, " + f"{self.city}, " + f"{self.country}")
i = Three("Acountry", "AnAddress", "Aphone", "Acity")
推荐阅读
- javascript - 如何以角度指定路由器出口?
- flutter - 如何仅显示列表中的特殊部分 FLUTTER
- iis - 托管在 IIS 上的 Dot Net Core 应用程序在系统重新启动时崩溃
- php - 如何使用数组更新多行
- android - Android JNI/C++/CMake:如何添加和构建相互依赖的 C++ 库?
- mysql - 基于第一个表中的值的连接表中的最大值
- maven - Serenity Cucumber Jenkins 作业在 [Error] WARNING 消息后挂起 10 多分钟
- python - 计算一个数组的每个元素乘以第二个数组的所有元素的累积和
- loopbackjs - 如何通过 Loopback 4 模型添加唯一约束?
- regex - 在 CMake 中,如何检查字符串是否包含整数?