python class继承dict,Python类继承和__dict__查找

Let's say I define class A:

>>> class A:

... a = 1

... class SubA:

... sub_a = { 'a': 1, 'b': 1}

Then I define class B that inherits from A:

>>> class B(A):

... pass

Now, check __dict__ of A and __dict__ of B:

>>> A.__dict__

{'a': 1, '__module__': '__builtin__', '__doc__': None, 'SubA': }

>>> B.__dict__

{'__module__': '__builtin__', '__doc__': None}

Somehow, B.__dict__ contains neither 'a' nor 'SubA'.

Now if we do:

>>> A.a

1

>>> B.a

1

>>> A.SubA

>>> B.SubA

First question: why B.__dict__ does not contain 'a' and 'SubA'?

Second question: Why B.a and B.SubA give the expected results, although neither 'a' nor 'SubA' is in B's __dict__?

Thanks!

解决方案

@bgporter has given a good explanation of the behaviour, I'll just go into why a little:

If your class variable was in B.__dict__, how would it function? Each subclass would have it's own value for a, independent of the value for A.a - this is not what you would expect. A class variable should exist once - in that class.

Instead, Python does a lookup on the class and if it doesn't exist, then looks up to it's base classes - note that means it is possible to shadow a class variable in a subclass.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值