Python 中的子类中的__init__() 函数会覆盖父类的函数,一些情况往往需要在子类里调用父类函数。
如下例程里,???处是需要调用父类函数的地方,接下来结合例程具体介绍。
- 1 1 # -*- coding:utf-8 -*-
- 2 2 class Student:
- 3 3 def __init__(self,name):
- 4 4 self.name=name
- 5 5 def ps(self):
- 6 6 print('I am %s'%self.name)
- 7 7
- 8 8 class Score(Student):
- 9 9 def __init__(self,name,score):
- 10 10 self.score=score
- 11 11 ???
- 12 12 def ps1(self):
- 13 13 print('I\'m %s,%s' %(self.name,self.score))
- 14 14
- 15 15 Score('Bob','99').ps()
- 16 16 Score('Bob','99').ps1()
Python3.5 中,通过查阅资料,有如下几种调用方式。
第一种是直接法。使用父类名称直接调用,形如 parent_class.parent_attribute(self),对应例程即语句:
- Student.__init__(self,name)
第二种是通过 super 函数,形如 super(child_class, child_object).parent_attribute(arg)。第一个参数表示调用父类的起始处,第二个参数表示类实例(一般使用 self),父类方法的参数只有 self 时,参数 args 不用写。此外,类内部使用时,child_class, child_object 也可省略。对应例程:
- super(Score,self).__init__(name)
或者:
- super().__init__(name)
在类外面也可使用 super 函数,但是要有 child_class, child_object 两个参数。
来源: http://www.bubuko.com/infodetail-1991899.html