python的super使用
2016-07-20 00:00
387 查看
本文讲述一下super的使用:
1:
运行结果:
这是简单的调用
当调用父类比较多的时候,在调用方法是遵循MRO C3线性处理法则,源码如下:
简单的讲述一下:
在调用的时候首先mro(A)=[A,O]
mro[B]=[B]+merge(mro(A)+[A])
=[B]+merge([A,O]+[A])
遍历执行merge操作的序列,如果一个序列的第一个元素,是其他序列中的第一个元素,或不在其他序列出现,则从所有执行merge操作序列中删除这个元素,合并到当前的mro中。
所以mro[B]=[B,A]+merge([O])=[B,A,O],同理mro[C]=[C,A,O]
mro[D]=[D]+merge(mro(B)+mro(C)+[B,C])
=[D]+merge([B,A,O]+[C,A,O]+[B,C])
=[D,B,C]+merge([A,O]+[A,O])
=[D,B,C,A]+merge([O]+[O])
=[D,B,C,A]
所以多父类的时候就遵循这个方式
1:
class A(object): def __init__(): print "I'm A" def test(self): print "I'm test" class B(A): def __init__(): super(B,self).__init__() def test_B(self): super(B,self).test() b=B() b.test_B()
运行结果:
这是简单的调用
当调用父类比较多的时候,在调用方法是遵循MRO C3线性处理法则,源码如下:
#-*- encoding:GBK -*-# def mro_C3(*cls): print len(cls) if len(cls)==1: print "hello" if not cls[0].__bases__: print cls return cls else: return cls+ mro_C3(*cls[0].__bases__) else: seqs = [list(mro_C3(C)) for C in cls ] +[list(cls)] res = [] while True: non_empty = list(filter(None, seqs)) if not non_empty: return tuple(res) for seq in non_empty: candidate = seq[0] not_head = [s for s in non_empty if candidate in s[1:]] if not_head: candidate = None else: break if not candidate: raise TypeError("inconsistent hierarchy, no C3 MRO is possible") res.append(candidate) for seq in non_empty: if seq[0] == candidate: del seq[0] class C(object): pass class A(C): pass class B(C): pass mro_C3(A,B)
简单的讲述一下:
#!/usr/bin/env python #--*-- coding: utf-8 --*-- class A(object): def __init__(self): print "enter A" print "leave A" class C(A): def __init__(self): print "enter C " super(C,self).__init__() def c(self): print "diaoyongfangfa" class B(A): def __init__(self): print "enter B" super(B,self).__init__() class D(B,C): def __init__(self): super(D,self).__init__() print "leave D" b = D() 结果:enter B enter C enter A leave A leave D >>>
在调用的时候首先mro(A)=[A,O]
mro[B]=[B]+merge(mro(A)+[A])
=[B]+merge([A,O]+[A])
遍历执行merge操作的序列,如果一个序列的第一个元素,是其他序列中的第一个元素,或不在其他序列出现,则从所有执行merge操作序列中删除这个元素,合并到当前的mro中。
所以mro[B]=[B,A]+merge([O])=[B,A,O],同理mro[C]=[C,A,O]
mro[D]=[D]+merge(mro(B)+mro(C)+[B,C])
=[D]+merge([B,A,O]+[C,A,O]+[B,C])
=[D,B,C]+merge([A,O]+[A,O])
=[D,B,C,A]+merge([O]+[O])
=[D,B,C,A]
所以多父类的时候就遵循这个方式
相关文章推荐
- python3字典、列表和json对象互转
- python(一) A+B
- python3操作mysql数据库增删改查
- python3判断字典、列表、元组为空以及字典是否存在某个key的方法
- python初级项目课(二)
- 【Python语法】python中__name__
- Python学习-1天--基础操作
- python3判断变量类型
- 利用python进行数据分析 第二章错误
- Python操作审计策略
- python魔法方法-反射运算和增量运算
- python-scrapy 中运行出现DLL load faild :%1 不是32位应用程序的问题
- python3常用的系统标准库
- python3的面向对象
- Java VS Python
- 以写代学:python 函数
- 二叉树的最大深度(leetcode-104)
- python
- Python logging使用指南
- python核心编程学习笔记-2016-07-19-03-局部变量代替模块变量