Python类的继承
来源:互联网 发布:域名过户流程 编辑:程序博客网 时间:2024/06/01 11:22
1、类的继承
语法:
class SubClassName (ParentClass1[, ParentClass2, ...]): 'Optional class documentation string' class_suite
在Python中继承中的一些特点:
1:在继承中基类的构造(__init__()方法)不会被自动调用,它需要在其派生类的构造中亲自专门调用。
2:在调用基类的方法时,需要加上基类的类名前缀,且需要带上self参数变量。区别于在类中调用普通函数时并不需要带上self参数。
3:Python总是首先查找对应类型的方法,如果它不能在派生类中找到对应的方法,它才开始到基类中逐个查找。
如果在继承元组中列了一个以上的类,那么它就被称作“多重继承”。
例如:
Parent类:
class Parent: # 定义父类 parentAttr = 100 def __init__(self): print("调用父类构造函数") def parentMethod(self): print("调用父类方法parentMethod") def setAttr(self, attr): Parent.parentAttr = attr def getAttr(self): print("父类属性 : ", Parent.parentAttr)
Child类:
from Parent import *class Child(Parent): # 定义子类 def __init__(self): print("调用子类构造方法") def childMethod(self): print("调用子类方法childMethod")
ChildTest类:
from Child import *c = Child() # 实例化子类c.childMethod() # 调用子类的方法c.parentMethod() # 调用父类方法c.setAttr(200) # 再次调用父类的方法c.getAttr() # 再次调用父类的方法
输出结果:
调用子类构造方法调用子类方法childMethod调用父类方法parentMethod父类属性 : 200
你可以使用issubclass()或者isinstance()方法来检测。issubclass(sub, sup)布尔函数判断一个类是另一个类的子类或者子孙类。isinstance(obj, Class)布尔函数如果obj是Class类的实例对象或者是一个Class子类的实例对象则返回true。
2、方法重写和运算符重载
如果你的父类方法的功能不能满足你的需求,你可以在子类重写你父类的方法。Python同样支持运算符重载。
阅读全文
0 0
- Python类的继承
- python类的继承
- Python 类的继承
- Python 类的继承
- Python类的继承
- Python类的继承
- python ---类的继承
- Python类的继承
- Python:类的继承
- python 类的继承
- Python 类的继承
- Python:类的继承
- Python--类的继承
- Python中类的继承
- Python类的继承示例
- python知识-类的继承
- Python 类的多继承
- Python中类的继承
- 选项卡react-native-scrollable-tab-view
- [Leetcode] 290. Word Pattern 解题报告
- Java线程初步
- 机器学习在线学习算法--迭代器实现
- OpenSessionInViewFilter 的配置及作用
- Python类的继承
- JAVA设计模式-概要
- div和span的区别
- 第一个缺失的正整数
- java-面向对象/类
- OpenGL内核模式学习笔记第0篇——写在开篇
- C/C++:sizeof运算符
- A. Restaurant Tables
- 递归