Python:为什么__dict__属性不在内置类实例中

时间:2012-02-29 15:46:29

标签: python

如果我对Python数据模型的理解是正确的,那么类和类实例都有关联的__dict__对象,其中包含所有属性。但是,我有点困惑为什么某些类实例(例如str的实例)没有__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 个答案:

答案 0 :(得分:11)

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

答案 1 :(得分:0)

添加到此:

您可以使用以下内容获得等效的只读__dict__

{s:getattr(x,s) for x in dir(x)}