解释 __dict__ 属性 [英] Explain __dict__ attribute
问题描述
我真的对 __dict__
属性感到困惑.我已经搜索了很多,但仍然不确定输出.
如果在对象、类或函数中使用此属性,有人可以从零开始解释它的使用吗?
基本上它包含了描述相关对象的所有属性.它可用于更改或读取属性.引用 __dict__
的文档><块引用>
用于存储对象(可写)属性的字典或其他映射对象.
请记住,在 Python 中一切都是对象.当我说一切时,我的意思是所有的东西,比如函数、类、对象等(是的,你没看错,类.类也是对象).例如:
def func():经过func.temp = 1打印(func.__dict__)类 TempClass:一 = 1def temp_function(self):经过打印(TempClass.__dict__)
会输出
{'temp': 1}{'__module__': '__main__','一':1,'temp_function':<函数 TempClass.temp_function at 0x10a3a2950>,'__dict__':<'TempClass' 对象的属性 '__dict__','__weakref__':<'TempClass' 对象的属性 '__weakref__','__doc__':无}
I am really confused about the __dict__
attribute. I have searched a lot but still I am not sure about the output.
Could someone explain the use of this attribute from zero, in cases when it is used in a object, a class, or a function?
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__
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:
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}
这篇关于解释 __dict__ 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!