Python学习21

python(python中的super函数)

1、python中的super函数

在python中,类里的__init__方法(函数)和属性,在类实例化的时候会被自动执行
在类的继承当中可能覆盖同名的方法,这样就不能调用父类的方法了,只能调用子类的构造方法

  • super函数:调用父类或者超类的方法(函数)和属性
  • super(super所在的类名,self).属性或者父类(超类)的方法(函数)和属性:这是python2.x中的写法
  • super().属性或者父类(超类)的方法(函数)和属性:这是python3.x中的写法,同时兼容2.x的写法
class person():
    
    def __init__(self):
        print('你出生啦!!!')
    
    def say(self):
        print('hello the world!!!')

class student(person):

    def __init__(self,sex,name):
        super().__init__()
        self.sex = sex
        self.name = name
        print('%s %s你上学啦!!!'%(sex,name))

    def getName(self):
        return self.name

    def say(self):
        super().say()
        print('hello my school!!!')
st = student('man','小明')
print(st.getName())
st.say()

输出:
你出生啦!!!
man 小明你上学啦!!!
小明
hello the world!!!
hello my school!!!

 

 

  • super()函数调用父类的父类(超类)类跨过三代的方法(函数)和属性
class person():

    def __init__(self):
        print('你出生啦!!!')
    
    def say(self):
        print('hello the world!!!')
    
    def runs(self):
        print('you can run')

class student(person):
    
    def __init__(self,sex,name):
        self.sex = sex
        self.name = name

    def getName(self):
        return self.name

    def say(self):
        super().say()
        print('hello my school!!!')

class myrun(student):
    def runs(self):
        super().runs()
        print('you can run fast')

runss = myrun('man','xioaming')
runsss = runss.runs()

输出:
you can run
you can run fast
posted @ 2020-12-31 15:10  MFTang  阅读(105)  评论(0编辑  收藏  举报