首页 > 解决方案 > 如何实现具有多个 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()在有效的原始代码中实现?

标签: pythonpython-3.xinheritancesuper

解决方案


您应该阅读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")

推荐阅读