• 技术文章 >常见问题 >Python常见问题

    python中子类可以调用父类方法吗

    silencementsilencement2019-10-25 16:19:36原创1935

    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):
    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脚本 下一篇:python空列表不能用append吗

    相关文章推荐

    • Python中类的继承是什么• Python多继承C3算法解析

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网