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?
ベストアンサー1
Basically it contains all the attributes which describe the object in question. It can be used to alter or read the attributes. Quoting from のドキュメント__dict__
オブジェクトの (書き込み可能な) 属性を格納するために使用される辞書またはその他のマッピング オブジェクト。
覚えておいてください、Python ではすべてがオブジェクトです。すべてとは、関数、クラス、オブジェクトなどすべてを意味します (はい、正しくはクラスです。クラスもオブジェクトです)。たとえば、次のようになります。
def func():
pass
func.temp = 1
print(func.__dict__)
class TempClass:
a = 1
def temp_function(self):
pass
print(TempClass.__dict__)
出力します
{'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}