今天学习的是刘金玉老师零基础Python教程110期调用父类同名方法,super函数。
一、super函数
super()这个方法用来解决子类中调用父类同名构造方法。Python版本过渡,在2.x版本中往往写成super(所在类的类名,self)这种形式,而在3.x版本开始后,就直接可以简写为super()来直接调用父类中的构造方法。
二、通过实际测试我们知道:
1.super方法可以用在类中的任意的函数中,去调用父类中的方法。
2.super方法也可以调用超类中的方法。student类是person类的子类,runstudent是student类的子类,那么我们可以称runstudent类是person类的超类。
三、案例
class person:
def __init__(self):
print("四川二流子从零开始学编程")
def say(self):
print("我是程序员")
class student(person):
def __init__(self,name):
super().__init__()
self.name=name
def getname(self):
return self.name
def say(self):
super(student,self).say()
print("我是假的程序员")
stu=student("王二")
print(stu.getname())
stu.say()