【问题标题】:Python subclass does not have __dict__ while the superclass has?Python 子类没有 __dict__ 而超类有?
【发布时间】: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:为什么Fooinstance 抛出AttributeErrorA 的字典为空。

【问题讨论】:

  • dir(Super)dir(Sub) 说什么?
  • 两者似乎都有 __dict__ 和 dir() 调用
  • 这里是some info 关于__dict__['__dict__'],但不清楚为什么它不在子类中。

标签: python class dictionary attributes built-in


【解决方案1】:

具有 slots 的类没有 dict。这里 'bar' 和 slots 之间存在冲突。删除'bar',它会正常工作。

【讨论】:

    猜你喜欢
    • 2011-06-20
    • 1970-01-01
    • 2023-03-23
    • 2012-05-16
    • 2011-04-07
    • 1970-01-01
    • 2018-03-27
    • 1970-01-01
    相关资源
    最近更新 更多