我正在阅读 python 描述符,那里有一行
Python first looks for the member in the instance dictionary. If it's not found, it looks for it in the class dictionary.
我真的很困惑什么是instance dict和什么是class dictionary
任何人都可以用代码向我解释那是什么
我以为他们是一样的
最佳答案
实例字典包含对分配给实例的所有对象和值的引用,类级别字典包含类命名空间中的所有引用。
举个例子:
>>> class A(object):
... def foo(self, bar):
... self.zoo = bar
...
>>> i = A()
>>> i.__dict__ # instance dict is empty
{}
>>> i.foo('hello') # assign a value to an instance
>>> i.__dict__
{'zoo': 'hello'} # this is the instance level dict
>>> i.z = {'another':'dict'}
>>> i.__dict__
{'z': {'another': 'dict'}, 'zoo': 'hello'} # all at instance level
>>> A.__dict__.keys() # at the CLASS level, only holds items in the class's namespace
['__dict__', '__module__', 'foo', '__weakref__', '__doc__']
关于python - 实例字典和类字典有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14795546/