wordpress整站主题,传媒公司logo设计创意,网页和网站设计,西安做网站xamokj目录
一.Python super 函数简介二.Python super 函数语法三.Python super 函数使用 1.案例一2.案例二#xff1a; 四.猜你喜欢 零基础 Python 学习路线推荐 : Python 学习目录 Python 基础入门 一.Python super 函数简介
Python 内置函数 super 主要用于类的多继承…目录
一.Python super 函数简介二.Python super 函数语法三.Python super 函数使用 1.案例一2.案例二 四.猜你喜欢 零基础 Python 学习路线推荐 : Python 学习目录 Python 基础入门 一.Python super 函数简介
Python 内置函数 super 主要用于类的多继承中用来查找并调用父类的方法所以在单重继承中用不用 super 都没关系但是使用 super 是一个好的习惯。一般我们在子类中需要调用父类的方法时才会这么用
二.Python super 函数语法 参数type — 类一般是类名object-or-type — 类,一般是 self返回值:无
super(type,object-or-type)三.Python super 函数使用
1.案例一
# !usr/bin/env python
# -*- coding:utf-8 _*-Author:猿说编程
Blog(个人博客地址): www.codersrc.com
File:Python super 函数.py
Time:2021/04/29 07:37
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(个人博客地址): www.codersrc.com
File:Python super 函数.py
Time:2021/04/29 07:37
Motto:不积跬步无以至千里不积小流无以成江海程序人生的精彩需要坚持不懈地积累class Dog:def __init__(self):self.fly Falsedef print_fly(self):if self.fly:print(不是普通狗能飞)else:print(普用狗不会飞)class xiaotianquan(Dog):def __init__(self):self.sound Truedef 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 完成例如
# !usr/bin/env python
# -*- coding:utf-8 _*-Author:猿说编程
Blog(个人博客地址): www.codersrc.com
File:Python super 函数.py
Time:2021/04/29 07:37
Motto:不积跬步无以至千里不积小流无以成江海程序人生的精彩需要坚持不懈地积累class Dog:def __init__(self):self.fly Falsedef print_fly(self):if self.fly:print(不是普通狗能飞)else:print(普用狗不会飞)class xiaotianquan(Dog):def __init__(self):super().__init__() # 等效 super(xiaotianquan,self).__init__()self.fly Trueself.sound Truedef print_sing(self):if self.sound:print(汪汪汪)else:print(假狗狗)if __name__ __main__:dog xiaotianquan()dog.print_sing()dog.print_fly()
输出结果汪汪汪不是普通狗能飞四.猜你喜欢
Python for 循环Python 字符串Python 列表 listPython 元组 tuplePython 字典 dictPython 条件推导式Python 列表推导式Python 字典推导式Python 函数声明和调用Python 不定长参数 *argc/**kargcsPython 匿名函数 lambdaPython return 逻辑判断表达式Python 字符串/列表/元组/字典之间的相互转换Python 局部变量和全局变量Python type 函数和 isinstance 函数区别Python is 和 区别Python 可变数据类型和不可变数据类型Python 浅拷贝和深拷贝
未经允许不得转载猿说编程 » Python super 函数