Python 解释 __dict__ 属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19907442/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Explain __dict__ attribute
提问by Zakos
I am really confused about the __dict__
attribute. I have searched a lot but still I am not sure about the output.
我真的对__dict__
属性感到困惑。我已经搜索了很多,但仍然不确定输出。
Could someone explain the use of this attribute from zero, in cases when it is used in a object, a class, or a function?
如果在对象、类或函数中使用此属性,有人可以从零开始解释它的使用吗?
回答by thefourtheye
Basically it contains all the attributes which describe the object in question. It can be used to alter or read the attributes.
Quoting from the documentation for __dict__
基本上它包含描述相关对象的所有属性。它可用于更改或读取属性。从文档中引用__dict__
A dictionary or other mapping object used to store an object's (writable) attributes.
用于存储对象(可写)属性的字典或其他映射对象。
Remember, everything is an object in Python. When I say everything, I mean everything like functions, classes, objects etc (Ya you read it right, classes. Classes are also objects). For example:
请记住,在 Python 中一切都是对象。当我说一切时,我的意思是所有的东西,比如函数、类、对象等(是的,你没看错,类。类也是对象)。例如:
def func():
pass
func.temp = 1
print(func.__dict__)
class TempClass:
a = 1
def temp_function(self):
pass
print(TempClass.__dict__)
will output
会输出
{'temp': 1}
{'__module__': '__main__',
'a': 1,
'temp_function': <function TempClass.temp_function at 0x10a3a2950>,
'__dict__': <attribute '__dict__' of 'TempClass' objects>,
'__weakref__': <attribute '__weakref__' of 'TempClass' objects>,
'__doc__': None}