Python学习--Super()
来源:互联网 发布:工业机器人编程软件 编辑:程序博客网 时间:2024/06/11 13:12
在python中,多重继承需要Python去进行相应的检查,而Python无法直接进行检测,这时就需要super()。
多重继承是指你定义的类继承了多个类,就像这样:
class SuperFun(Child, BadStuff):
pass
这相当于说“创建一个叫 SuperFun 的类,让它同时继承 Child 和 BadStuff ”。
这里一旦你在 SuperFun 的实例上调用任何隐式动作,Python 就必须回到类的层次结构中去检查 Child 和 BadStuff ,而且必须要用固定的次序去检查。为实现这一点 Python 使用了一个叫 “方法解析顺序(Method Resolution Order,MRO)”的东西,还用了一个叫 C3 的算法。由于有这个复杂的 MRO 和这个很好的算法,Python 总不该把这些事情留给你去做吧,不然你不就跟着头大了?所以 Python 给你这个 super() 函数,用来在各种需要修改行为的场合为你处理,就像上面 Child.altered 一样。有了 super() ,妈妈再也不用担心我吧继承关系弄糟,因为 Python 会给我找到正确的函数。
super() 和 init 搭配使用
最常见的 super() 的用法是在基类的 init 函数中使用。通常这也是唯一可以进行这种操作的地方,在这里你在子类里做了一些事情,然后完成对父类的初始化。这里是一个在 Child 中完成上述行为的例子: class Child(Parent):
def __init__(self, stuff):
self.stuff = stuff
super(Child, self).__init__()
这和上面的 Child.altered 差别不大,只不过我在 init 里边先设了个变量,然后才用
Parent.init 初始化了 Parent 。
- Python学习super()
- Python学习--Super()
- python 之 super函数学习
- Python学习:多继承和super()
- Python学习笔记 --- 学会super用法
- python--super
- python super
- python: super
- python super()
- python super()
- python super
- python super()
- python super()
- python super()
- python - super
- Python Super
- python super()
- python super()
- LeetCode 31.Next Permutation
- python----高效的解释性语言
- 【arm】ubuntu mate apt-get 404 not found
- MySQL简单语法(7)
- 制作一个带圆角选择器的Button
- Python学习--Super()
- Android中WebView使用详解
- 动态调用差C++类库的方法(C#)
- 拓展kmp算法总结
- spark-sql使用
- 数据结构之栈(以字符反转和分隔符匹配为例子)
- Go的工作空间
- ZkClient之读取数据。
- dos调用matlab进行定时任务处理