Boi*_*ota 1 python oop inheritance parent-child python-2.7
在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 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())
Run Code Online (Sandbox Code Playgroud)
只要__init__()签名兼容,您就可以使用实例的类型而不是显式类型。
class Parent(object):
def __str__(self):
return 'I am a Parent'
def reproduce(self):
# do stuff common to all subclasses.
print('parent reproduction')
# then return an instance of the caller's type
return type(self)()
class Child(Parent):
def __str__(self):
return 'I am a Child'
def reproduce(self):
# do stuff specific to Child.
print('child reproduction')
# call the parent's method but it will return a
# Child object
return super(Child, self).reproduce()
print(Parent().reproduce())
parent reproduction
I am a Parent
print(Child().reproduce())
child reproduction
parent reproduction
I am a child
Run Code Online (Sandbox Code Playgroud)