2012-02-29 49 views
6

如果我对Python数据模型的理解是正确的,那么类和类实例都具有包含所有属性的相关__dict__对象。然而,我有些困惑,为什么某些类实例,例如str的实例,没有__dict__属性。Python:为什么__dict__属性不在内置类实例中

如果我创建一个自定义类:

class Foo: 
    def __init__(self): 
      self.firstname = "John" 
      self.lastname = "Smith" 

那么我可以说得到的实例变量:

>>> f = Foo() 
>>> print(f.__dict__) 
{'lastname': 'Smith', 'firstname': 'John'} 

但如果我尝试做同样与内置的一个实例在str,我得到:

>>> s = "abc" 
>>> print(s.__dict__) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
AttributeError: 'str' object has no attribute '__dict__' 

那么,为什么不的str实例有一个__dict__属性?

+2

为了详细说明这一点,如果每个字典有'__dict__'的话,那就也必须是'__dict __.__ dict__' - 递归有多深? – 2016-01-29 09:29:10

回答

10

C中定义的类型实例默认情况下没有__dict__属性。

0

只需添加到此:

您可以使用该得到的等值只__dict__阅读:

{s:getattr(x,s) for x in dir(x)} 
相关问题