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