Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Built-in Class Attribute __dict__ ใน Python ทำอะไร

Special Attribute ของทุกโมดูลคือ __dict__ เป็น Dictionary ที่เก็บ Symbol Table ของโมดูล

object.__dict__

Dictionary หรือ Mapping Object ใช้เก็บ Attributes (Writable) ของ Object

ตัวอย่าง

class MyClass(object):
    class_var = 1
    def __init__(self, i_var):
        self.i_var = i_var

foo = MyClass(2)
bar = MyClass(3)

print(MyClass.__dict__)
print(foo.__dict__)
print(bar.__dict__)

ผลลัพธ์

{'__module__': '__main__', 'class_var': 1, '__dict__': ..., '__weakref__': ..., '__doc__': None, '__init__': ...}
{'i_var': 2}
{'i_var': 3}

MyClass.__dict__ มี Class Attributes และ Methods ส่วน foo.__dict__ และ bar.__dict__ มี Instance Attributes เท่านั้น