python - 实例字典和类字典有什么区别

标签 python

我正在阅读 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/

相关文章:

python - 将带有嵌套数组的 JSON 转换为 CSV

python - 有条件地访问 Python 中的项目

python - Django Mandrill 电子邮件编码

python - 如何在 python 数据框中做季度?

python - Process.StandardOutput.Readline() 卡在 Mono 而不是 .NET

python flask threaded true 不工作

python - 尽管由 Conda 安装,但未找到 cx_Oracle

python - 在python中,如何使函数接受相同的小写和大写字母?

python - 安装http-request-randomizer会导致安装错误

python - 如何在静态文件夹中使用 Flask 中的 opencv 显示新保存的图像?