【发布时间】:2012-02-29 15:46:28
【问题描述】:
如果我对 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__ 属性?
【问题讨论】:
-
详细说明一下,如果每个字典都有
__dict__,那么也必须有__dict__.__dict__——递归应该走多远?
标签: python