在ResistantVirus
类的reproduce
方法中,我试图调用SimpleVirus
类的reproduce(self, popDensity)
,但是我希望它返回一个SimpleVirus
对象,而不是返回一个ResistantVirus
对象。在
显然,我也可以重复SimpleVirus.reproduce
方法中的一些代码,并在我的ResistantVirus.reproduce
方法中使用相同的实现,但是我想知道是否可以调用并重写{
class SimpleVirus(object):
def __init__(self, maxBirthProb, clearProb):
self.maxBirthProb = maxBirthProb
self.clearProb = clearProb
def reproduce(self, popDensity):
if random.random() > self.maxBirthProb * (1 - popDensity):
raise NoChildException('In reproduce()')
return SimpleVirus(self.getMaxBirthProb(), self.getClearProb())
class ResistantVirus(SimpleVirus):
def __init__(self, maxBirthProb, clearProb, resistances, mutProb):
SimpleVirus.__init__(self, maxBirthProb, clearProb)
self.resistances = resistances
self.mutProb = mutProb
def reproduce(self, popDensity)
## returns a new instance of the ResistantVirus class representing the
## offspring of this virus particle. The child should have the same
## maxBirthProb and clearProb values as this virus.
## what I sketched out so far and probs has some mistakes:
for drug in activeDrugs:
if not self.isResistantTo(drug):
raise NoChildException
break
simple_virus = SimpleVirus.reproduce(self,popDensity)
return ResistantVirus(simple_virus.getMaxBirthProb(),simple_virus.getClearProb())
只要
__init__()
签名兼容,就可以使用实例的类型而不是显式类型。在使用super调用父类的方法:
看起来^{} 可以帮你。在
copy方法将携带
^{pr2}$self
是什么的类(不一定是父类)。例如:这似乎是你的主要目标。然而,在如何构建测试结构方面也值得付出一些努力。我使用您的示例代码实现了一个不同的解决方案,它允许您继承测试。请注意,需要向病毒传递一个关键字参数列表(
**kwargs
)。下面给出了用法示例。在下面的内容有时会复制,有时会引发
Exception
。在请注意,这两个类之间没有显著的代码重用。如果你有一个严格的继承链,并且事情会随着你的发展而“积累”,这是很好的。但是,如果有很多类都继承
SimpleVirus
,并且其中一些类共享功能,那么值得研究一下object composition over inheritance。在相关问题 更多 >
编程相关推荐