10行代码解释super最常用的情形

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}
描述符

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值