【发布时间】:2021-12-09 23:34:39
【问题描述】:
我是 Python 新手,但有一些东西让我对类继承感到疯狂,我在网上找到的所有解决方案都对我不起作用,我无法理解原因。
我有一个课程Bond,其中有一个我们将投资于它们的条款、一定的投资金额、最低价格、最低期限和年利率。子类LongTerm 的最短期限为 2 年,最低金额为 250 美元,年利率为 2.5%。
以下代码可以正常工作:
class Bond(object):
def __init__(self,minTerm, term,amount,minPrice,yrlyRate):
self.term = term
self.amount = amount
self.minPrice = minPrice
self.minTerm = minTerm
self.yrlyRate = yrlyRate
class LongTerm(Bond):
def __init__(self, term,amount,minPrice, minAmount = 1000, minTerm = 5, yrlyRate = 0.05):
self.term = term
self.amount = amount
self.minPrice = minPrice
self.minAmount = minAmount
self.minTerm = minTerm
self.yrlyRate = yrlyRate
但是当我使用部分继承功能时
super().__init__(term,amount,minPrice)
显示错误:
TypeError: __init__() missing 2 required positional arguments: 'minPrice' and 'yrlyRate'
使用super()的代码:
class Bond(object):
def __init__(self,minTerm, term,amount,minPrice,yrlyRate):
self.term = term
self.amount = amount
self.minPrice = minPrice
self.minTerm = minTerm
self.yrlyRate = yrlyRate
class LongTerm(Bond):
def __init__(self, term,amount,minPrice, minAmount = 1000, minTerm = 5, yrlyRate = 0.05):
super().__init__(term,amount,minPrice)
self.term = term
self.amount = amount
self.minPrice = minPrice
为什么我不能只部分继承超类的某些实例?
【问题讨论】:
-
顺便说一句,你不需要从
object继承,这仅在Python2.x或类似的东西中是必需的,基本上它应该只是class Bond: -
如果您从 Bond 继承,那么您将自己绑定到由其“init()”方法建立的合同。您应该遵守该合同,或者您可能不想要继承。
-
所以我不能做部分继承?我应该像在第一组代码中那样重新编写实例吗?
-
@Foucault 你可以重组第一个类来做类似
def __init__(*args)的事情,然后只有当len(args)大于某个值时才分配其余的值?或者使用默认值,或者你不需要部分继承,你仍然像在父类中一样使用子类中的所有参数,然后一些和那些额外的参数是你在子类中分配的参数 -
没有“部分继承”之类的东西,要么全有,要么全无。见Liskov substitution principle。
标签: python python-3.x oop inheritance