python子类怎么修改父类方法_在Python中如何从子类调用和重写父类方法

看起来^{}可以帮你。在import copy

class Parent(object):

def __init__(self, a):

self.a = a

def copy(self):

return copy.deepcopy(self)

class Child(Parent):

def __init__(self, a, b):

super(Child, self).__init__(a)

self.b = b

copy方法将携带self是什么的类(不一定是父类)。例如:

^{pr2}$

这似乎是你的主要目标。然而,在如何构建测试结构方面也值得付出一些努力。我使用您的示例代码实现了一个不同的解决方案,它允许您继承测试。请注意,需要向病毒传递一个关键字参数列表(**kwargs)。下面给出了用法示例。在import copy, random

class SimpleVirus(object):

def __init__(self, max_birth_prob, clear_prob):

self.max_birth_prob = max_birth_prob

self.clear_prob = clear_prob

self._tests = [self.simple_test]

def copy(self):

return copy.deepcopy(self)

def simple_test(self, **kwargs):

return random.random() < self.max_birth_prob * (1 - kwargs['pop_density'])

def reproduce(self, **kwargs):

if all(test(**kwargs) for test in self._tests):

return self.copy()

raise Exception

class ResistantVirus(SimpleVirus):

def __init__(self, max_birth_prob, clear_prob, resistances, mut_prob):

super(ResistantVirus, self).__init__(max_birth_prob, clear_prob)

self.resistances = resistances

self.mut_prob = mut_prob

self._tests.append(self.resistance_test)

def resistance_test(self, **kwargs):

return all(drug in self.resistances for drug in kwargs['drug_list'])

下面的内容有时会复制,有时会引发Exception。在res_virus = ResistantVirus(0.8, 0.2, ['a', 'b', 'c'], 0.1)

res_virus.reproduce(pop_density=0.3, drug_list=['a', 'b'])

请注意,这两个类之间没有显著的代码重用。如果你有一个严格的继承链,并且事情会随着你的发展而“积累”,这是很好的。但是,如果有很多类都继承SimpleVirus,并且其中一些类共享功能,那么值得研究一下object composition over inheritance。在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值