Python 类继承,super()
我刚开始掌握课程的诀窍,所以我想我应该试着做一个简单的人口动力学程序来练习。我不太明白如何实现super()。我读了一些旧帖子和其他在线论坛的东西,但我什么都做不到。有人能给我解释一下原因吗Python 类继承,super(),python,class,inheritance,python-2.7,Python,Class,Inheritance,Python 2.7,我刚开始掌握课程的诀窍,所以我想我应该试着做一个简单的人口动力学程序来练习。我不太明白如何实现super()。我读了一些旧帖子和其他在线论坛的东西,但我什么都做不到。有人能给我解释一下原因吗 class Females(object): '''Female population settings. Defines the pregnancy rates, death rates, and live births for a year.''' def __init__(
class Females(object):
'''Female population settings. Defines the pregnancy rates, death rates,
and live births for a year.'''
def __init__(self,female):
super(Females,self).__init__()
self.female = female
self.live_birth
def __str__(self):
return 'Current female population: {0}'.format(str(self.female))
def death(self):
self.female_death_oldage=int((randint(0,50)*0.01)*female)
return self.female_death_oldage
def pregnancies(self):
self.female_pregnancies=int(((randint(0,100)*0.01)*female)*0.2)
return self.female_pregnancies
def live_birth(self):
self.live_births=int(self.female_pregnancies*((randint(0,100)*0.01)))
return self.live_births
def total_females(self):
self.next_female_generation = female - self.female_death_oldage
class Babies(Females):
def __init__(self):
super(Babies,self).__init__()
def babies_born(self):
self.little_girls = int(self.live_births*(randint(0,100)*0.01))
self.little_boys = (self.live_births - self.little_girls)
return self.little_boys,self.little_girls
if __name__=='__main__':
x=Males(male)
y=Females(female)
b=Babies()
print '%r males died from old age' % x.death()
print '%r females became pregnant' % y.pregnancies()
print 'There were %r live births' % y.live_births()
print b.babies_born()
当我尝试运行它(使用EclipseJuno)时,我得到以下结果:
File "/Users/me/Documents/Coding/Population/Population.py", line 78, in <module>
b=Babies()
File "/Users/me/Documents/Coding/Population/Population.py", line 56, in __init__
super(Babies,self).__init__()
TypeError: __init__() takes exactly 2 arguments (1 given)
文件“/Users/me/Documents/Coding/Population/Population.py”,第78行,在
b=婴儿()
文件“/Users/me/Documents/Coding/Population/Population.py”,第56行,在__
超级(婴儿,自我)。\uuuuu init\uuuuuuuu()
TypeError:\uuuu init\uuuuuu()正好接受2个参数(给定1个)
super
用于调用类的基类
Babies
基类是Females
,因为Females
类构造函数需要两个参数,您需要向它传递两个参数
super(Babies, self).__init__('Mary')
这相当于:
Females.__init__(self, 'Mary')
但是super是首选,因为您不需要明确提到super类的名称。婴儿的超类是女性,它的init需要两个参数:self和Female
super(Babies,self)。\uuu init\uuu()
只使用一个参数调用它,隐式self
缺少第二个参数。我不知道如何将活产方法从雌性类调用到Babies
类中。我在Babies
类中需要super()吗?@Matt你的意思是如何调用未被子类重新实现的超类的方法?只需执行subclass\u instance.\u method()
@Matt即可从婴儿实例调用live\u delivers
方法,无需使用super
,只需从婴儿实例调用即可<当需要调用在子类中重写的基类的方法时,需要code>super
。