我想进行多重继承,使子类继承两个不同的超类。该子类应该有一个
__init__
方法,其中使用预期参数调用超类的 __init__
方法。
这是一个可以说明我的问题的例子:
class Place:
def __init__(self, country, city, **attr):
self.country = country
self.city = city
self.attributes = attr
def show_location(self):
print(self.country, self.city)
class Product:
def __init__(self, price, currency = '$'):
self.price = price
self.currency = currency
def show_price(self):
print(self.price, self.currency)
class Flat(Place, Product):
def __init__(self, country, city, street, number, price, currency = '$', **attr):
super(Place).__init__(country, city, **attr)
super(Product).__init__(price, currency)
self.street = street
self.number = number
def show_address(self):
print(self.number, self.street)
myflat = Flat('Mozambique', 'Nampula', 'Rua dos Combatentes', 4, 150000, '$')
但我真的不知道如何使用
super()
方法,并且此代码抛出以下错误:
TypeError: super() argument 1 must be type, not str
我想知道如何将
Flat
对象初始化为 Place
和 Product
...
在这种情况下使用
super()
是否合适?
还是这样直接打电话给
__init__
比较好:SuperClass.__init__(self, ...)
?
你很接近。您滥用了 super() 方法。使用 super() 时,您需要提供类本身作为第一个参数,而不是其名称作为字符串。另外,您需要将当前类(Flat)的实例作为第二个参数传递给 super()。如果您遇到任何其他问题,请告诉我。