python培训之子类可以调用父类方法吗

发布时间:2022-09-28 09:45:30 人气:140 作者:多测师

  Python中的子类中的__init__()函数会覆盖父类的函数,一些情况往往需要在子类里调用父类函数。

  如下例程里,处是需要调用父类函数的地方,接下来结合例程具体介绍。

  1 # -*- coding:utf-8 -*-

  2 class Student:

  3 def __init__(self,name):

  4 self.name=name

  5 def ps(self):

  6 print('I am %s'%self.name)

  7

  8 class Score(Student):

  9 def __init__(self,name,score):

python培训之子类可以调用父类方法吗

  10 self.score=score

  11 ???

  12 def ps1(self):

  13 print('I\'m %s,%s' %(self.name,self.score))

  14

  15 Score('Bob','99').ps()

  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两个参数。

  以上内容为大家介绍了python培训之子类可以调用父类方法吗,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注多测师。https://www.e70w.com/xwzx/


返回列表
在线客服
联系方式

热线电话

17727591462

上班时间

周一到周五

二维码
线