在reproduce方法ResistantVirus类,我试图调用reproduce(self, popDensity)的SimpleVirus类,但而不是返回SimpleVirus的对象,我希望它返回一个ResistantVirus对象。
显然,我也可以从SimpleVirus.reproduce方法中重复一些代码并在我的ResistantVirus.reproduce方法中使用相同的实现,但我想知道是否可以调用和覆盖SimpleVirus.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 …Run Code Online (Sandbox Code Playgroud)