如果我对Python数据模型的理解是正确的,那么类和类实例都具有__dict__包含所有属性的关联对象.但是,我有点困惑为什么某些类实例(例如,例如实例)str没有__dict__属性.
如果我创建一个自定义类:
class Foo:
def __init__(self):
self.firstname = "John"
self.lastname = "Smith"
Run Code Online (Sandbox Code Playgroud)
然后我可以通过说:
>>> f = Foo()
>>> print(f.__dict__)
{'lastname': 'Smith', 'firstname': 'John'}
Run Code Online (Sandbox Code Playgroud)
但是如果我尝试对内置的实例做同样的事情str,我得到:
>>> s = "abc"
>>> print(s.__dict__)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute '__dict__'
Run Code Online (Sandbox Code Playgroud)
那么,为什么不str具有__dict__属性的实例呢?