• 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
  • 相关阅读:
    spring学习10-AOP
    spring学习9-代理模式
    spring学习6-bean的自动装配
    PyQT5使用心得
    Python 时间戳和日期相互转换
    requests模块的入门使用
    Celery异步任务
    MySQL和python交互
    MySQL高级
    MySQL中select的使用
  • 原文地址:https://www.cnblogs.com/tangmf/p/14216899.html
Copyright © 2020-2023  润新知