小编Boi*_*ota的帖子

如何从 Python 中的子类调用和覆盖父类方法

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)

python oop inheritance parent-child python-2.7

1
推荐指数
1
解决办法
7506
查看次数

标签 统计

inheritance ×1

oop ×1

parent-child ×1

python ×1

python-2.7 ×1