Python 父子类继承笔记
来源:互联网 发布:足球数据分析软件 编辑:程序博客网 时间:2024/05/29 13:20
单项继承
简介:继承者含有被继承者的所有属性方法或函数。
例如:
class Parent: def hello(self): print("父类方法")class Child(Parent): pass # python有自己的语法标准,当我希望类是空实现的时候。 # 是不符合python的语法标准的,所以不能通过编译, # 但我通过pass关键字显式的告诉解释器,这里是空实现。a = Parent()a.hello()b = Child()b.hello()
Child内虽然只有pass,但它包含了Parent的所有函数。所以a.hello()和b.hello()运行会显示相同效果。
效果如下:
a = Parent()a.hello()父类方法b = Child()b.hello()父类方法
如果子类的函数名于父类的函数名冲突,那么子类的函数会覆盖父类的同名函数。
例如:
class Parent: def hello(self): print("父类方法")class Child(Parent): def hello(self): print("子类方法")b = Child()b.hello()
这里的b.hello()会显示子类方法。
b = Child()b.hello()子类方法
若父子类含有同名函数且想要实现父类的函数,那么就有两种方法解决。
1,调用未绑定的父类方法
class Parent: def hello(self): print("父类方法")class Child(Parent): def hello(self): Parent.hello(self) #只需要把需要的父类的函数加到子类中就行 print("子类方法")b = Child()b.hello()
效果如下:
b = Child()b.hello()父类方法
2,使用super函数
简介:自动找到基类(父类)的方法并传入参数。
class Parent: def hello(self): print("父类方法")class Child(Parent): def hello(self): super().hello() #添加函数super自动寻找基类的函数并传入参数 print("子类方法")b = Child()b.hello()
效果如下
b = Child()b.hello()父类方法
多重继承
简介:子类同时继承多个父类的属性。
class A: def A1(self): print("我代表A")class B: def B1(self): print("我代表B")class C(A, B): passc = C()c.A1()c.B1()
效果如下:
c.A1()我代表Ac.B1()我代表B
注:多重函数虽然功能强大,但是容错率极低。故不到万不得已,就不要用多重函数!
阅读全文
2 0
- Python 父子类继承笔记
- python中类的创建,父子类的继承
- 继承、父子类、单继承、多继承
- Python 笔记 : 类和继承
- 【Python】Python学习笔记(类的继承)
- java父子类继承(1)
- 父子类继承时候各部分执行顺序
- python之自动生成C++的父子双向继承关系
- Python笔记——类与继承
- Python学习笔记(11):类的继承
- 【Python】笔记:类继承问题总结
- 《python》学习笔记(Day5),继承类
- python学习笔记--继承
- Python初学笔记-继承
- 构造方法--父子继承
- hibernate继承关系父子类查询问题解析
- 继承、方法覆盖、父子类属性引用相关问题
- C++父子类继承时的隐藏、覆盖、重载
- RAC 中的双向数据绑定 RACChannel
- leetcode-java.T011_ContainerWithMostWater 找两条竖线然后这两条线以及X轴构成的容器能容纳最多的水
- Android快速实现热更新
- 数学符号
- leetcode-java.T009_PalindromeNumber 回文数字
- Python 父子类继承笔记
- leetcode-java.T008_StringToInteger 字符串转成整形
- 解决安卓style文件中设置Activity退出动画无效或者被干扰的问题
- leetcode-java.T007_ReverseInteger 整数翻转
- 一个老程序员写给换行业的朋友的信
- 在前端开发过程中遇到的问题1
- leetcode-java.T005_LongestPalindromicSubstringTotal 给定一个字符串S,找出它的最大的回文子串
- leetcode-java.T003_LongestSubstringWithoutRepeatingCharacters 给定一个字符串,找字符中的最大非重复子串
- Python ——raise