python的__mro__与__slot__

python支持多重继承,在解析父类的__init__时,定义解析顺序的是子类的__mro__属性,内容为一个存储要解析类顺序的元组。

 

class A(object):
    def __init__(self):
        print '    -> Enter A'
        print '    <- Leave A'

class B(A):
    def __init(self):
        print '    -> Enter B'
        # A.__init__(self)
        super(B, self).__init__()
        print '    <- Leave B'

class C(A):
    def __init__(self):
        print "    -> Enter C"
        # A.__init__(self)
        super(C, self).__init__()
        print "    <- Leave C"

class D(B, C):
    def __init__(self):
        print "    -> Enter D"
        # B.__init__(self)
        # C.__init__(self)
        super(D, self).__init__()
        print "    <- Leave D"

if __name__ == "__main__":
    d = D()
    print "MRO:", [x.__name__ for x in D.__mro__]
    print type(D.__mro__)

执行以上代码,得到的输出为:

-> Enter D
-> Enter C
-> Enter A
<- Leave A
<- Leave C
<- Leave D
MRO: ['D', 'B', 'C', 'A', 'object']
<type 'tuple'>

 

与之前一篇文章中的内容不同,类B并没有被执行,也许是因为没有显式调用,而C与B有相同父类。

尽量避免使用非绑定方法,可能会造成重复调用。

 

关于__slot__

__slot__定义类中可以被外界访问的属性,类似node中的exports。

当父类中定义了__slot__时,不能向父类中添加属性。如果子类中没有定义__slot__,则子类不受父类__slot__定义的限制。

如果父类与子类中都定义了__slot__,则邮箱的结果为父类与子类__slot__的合集。

 

转载于:https://www.cnblogs.com/harelion/p/4869346.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值