39.python super函数

您所在的位置:网站首页 pythonsuper() 39.python super函数

39.python super函数

#39.python super函数| 来源: 网络整理| 查看: 265

一.super函数简介

python内置函数super()主要用于类的多继承中,用来查找并调用父类的方法,所以在单重继承中用不用 super 都没关系;但是,使用 super() 是一个好的习惯。一般我们在子类中需要调用父类的方法时才会这么用;

二.super函数语法super(type,object-or-type)

参数:

type — 类,一般是类名;

object-or-type — 类,一般是 self;

返回值:无

三super函数使用1.案例一:# !usr/bin/env python # -*- coding:utf-8 _*- """ @Author:何以解忧 @Blog(个人博客地址): https://www.codersrc.com/   @File:python_super.py @Time:2019/12/29 21:25   @Motto:不积跬步无以至千里,不积小流无以成江海,程序人生的精彩需要坚持不懈地积累! """   class A:     def m(self):         print('A')   class B:     def m(self):         print('B')   class C(A):     def m(self):         print('C')         super().m()   C().m()

输出结果:

C A

代码分析:

这样做的好处就是:如果你要改变子类继承的父类(由A改为B),你只需要修改一行代码(class C(A): -> class C(B))即可,而不需要在class C的大量代码中去查找、修改基类名,另外一方面代码的可移植性和重用性也更高。

2.案例二:# !usr/bin/env python # -*- coding:utf-8 _*- """ @Author:何以解忧 @Blog(个人博客地址): https://www.codersrc.com/   @File:python_super.py @Time:2019/12/29 21:25   @Motto:不积跬步无以至千里,不积小流无以成江海,程序人生的精彩需要坚持不懈地积累! """   class Dog:     def __init__(self):           self.fly = False     def print_fly(self):           if self.fly:                print('不是普通狗,能飞')           else:                print('普用狗不会飞')   class xiaotianquan(Dog):      def __init__(self):          self.sound = True        def print_sing(self):           if self.sound:               print("汪汪汪")           else:               print("假狗狗")   if __name__ == '__main__':     dog = xiaotianquan()     dog.print_sing()  # 能正常输出     dog.print_fly()  # 报错,AttributeError: 'xiaotianquan' object has no attribute 'fly'

代码分析:

虽然子类xiaotianquan继承父类Dog,但是子类直接调用父类的print_fly函数,依然会报错,因为子类没有父类的fly属性,上面代码可以通过在__init__函数中调用super()完成,例如:

class Dog:     def __init__(self):           self.fly = False     def print_fly(self):           if self.fly:                print('不是普通狗,能飞')           else:                print('普用狗不会飞')   class xiaotianquan(Dog):      def __init__(self):          super().__init__() # 等效  super(xiaotianquan,self).__init__()          self.fly = True          self.sound = True          def print_sing(self):           if self.sound:               print("汪汪汪")           else:               print("假狗狗")   if __name__ == '__main__':     dog = xiaotianquan()     dog.print_sing()       dog.print_fly()

输出结果:

汪汪汪 不是普通狗,能飞


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3