super类和多重继承,C3算法,Python属性查找及其钩子
descriptor描述符
class super(object):
def __init__(self, cls, instance):
mro=instance.__class__.__mro__
self.instance=instance
self.next_parent=mro[mro.index(cls)+1]
def __getattribute__(self, name):
get=object.__getattribute__
func=get(get(self, 'next_parent'), name)
instance=get(self, 'instance')
return lambda *args, **kwargs:func(instance, *args, **kwargs)
class r(object):
def f(self, *args, **kwargs):
pass
class a(r):
def f(self, *args, **kwargs):
print('a', args, kwargs)
super(a, self).f(*args, **kwargs)
class b(r):
def f(self, *args, **kwargs):
print('b', args, kwargs)
super(b, self).f(*args, **kwargs)
class c(r):
def f(self, *args, **kwargs):
print('c', args, kwargs)
super(c, self).f(*args, **kwargs)
class d(a, b):
def f(self, *args, **kwargs):
print('d', args, kwargs)
super(d, self).f(*args, **kwargs)
class e(b, c):
def f(self, *args, **kwargs):
print('e', args, kwargs)
super(e, self).f(*args, **kwargs)
class f(a, c):
def f(self, *args, **kwargs):
print('f', args, kwargs)
super(f, self).f(*args, **kwargs)
class g(d, e, f):
def f(self, *args, **kwargs):
super(g, self).f(*args, **kwargs)
if __name__=='__main__':
g().f(1, 2, 3, a=1, b=2, c=3)
结果
d (1, 2, 3) {'a': 1, 'c': 3, 'b': 2}
e (1, 2, 3) {'a': 1, 'c': 3, 'b': 2}
f (1, 2, 3) {'a': 1, 'c': 3, 'b': 2}
a (1, 2, 3) {'a': 1, 'c': 3, 'b': 2}
b (1, 2, 3) {'a': 1, 'c': 3, 'b': 2}
c (1, 2, 3) {'a': 1, 'c': 3, 'b': 2}
描述符