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
python新手代码错了应该怎么改
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):
py()
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.mut_prob = mut_prob
self._tests.sistance_test)
def resistance_test(self, **kwargs):
return all(drug sistances for drug in kwargs['drug_list'])
下⾯的内容有时会复制,有时会引发Exception。在res_virus = ResistantVirus(0.8, 0.2, ['a', 'b', 'c'], 0.1)
produce(pop_density=0.3, drug_list=['a', 'b'])
请注意,这两个类之间没有显著的代码重⽤。如果你有⼀个严格的继承链,并且事情会随着你的发展⽽“积累”,这是很好的。但是,如果有很多类都继承SimpleVirus,并且其中⼀些类共享功能,那么值得研究⼀下object composition over inheritance。在

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。