【发布时间】:2013-11-18 19:47:53
【问题描述】:
在下面的示例中,超类具有__dict__ 属性,而子类没有。
>>> class Super(object):
... def hello(self):
... self.data1="hello"
...
>>>
>>> class Sub(Super):
... def hola(self):
... self.data2="hola"
...
>>>
>>> Super.__dict__
<dictproxy object at 0x108794868>
>>> Super.__dict__.keys()
['__dict__', '__module__', '__weakref__', 'hello', '__doc__'] # note __dict__
>>> Sub.__dict__.keys()
['__module__', '__doc__', 'hola'] #__dict__ absent here
>>> Sub.__dict__
<dictproxy object at 0x108794868>
Q1:上面的 cmets 显示了 dict 存在的位置。为什么超类有它而不是子类。
在试图找出答案时,我遇到了这个post.,这让我更加困惑。
>>> class Foo(object):
... __slots__ = ('bar',)
... bar="spam"
...
>>> f = Foo()
>>> f.__dict__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Foo' object has no attribute '__dict__'
>>> class A(object):
... pass
...
>>> b = A()
>>> b.__dict__
{}
Q2:为什么Foo 的instance 抛出AttributeError 但A 的字典为空。
【问题讨论】:
-
dir(Super)和dir(Sub)说什么? -
两者似乎都有
__dict__和 dir() 调用 -
这里是some info 关于
__dict__['__dict__'],但不清楚为什么它不在子类中。
标签: python class dictionary attributes built-in