zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    校园商铺-8商品模块-12接触商品与某商品类别的关联的实现
    centos 7访问windows共享文件夹
    怎样在CentOS 7.0上安装和配置VNC服务器
    【总结】教你怎么将centos7打造成桌面系统
    Centos 7安装gvim
    CentOS 7 安装virtualBox
    Centos 7中 vim 中文乱码
    CentOS 7 gedit编辑器中文乱码解决方法
    centos7支持ntfs
    delta
  • 原文地址:https://www.cnblogs.com/tangmf/p/14216899.html
Copyright © 2011-2022 走看看