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

แอตทริบิวต์คลาสในตัว __dict__ ทำอะไรใน Python


คุณลักษณะพิเศษของทุกโมดูลคือ __dict__ นี่คือพจนานุกรมที่มีตารางสัญลักษณ์ของโมดูล

object.__dict__

พจนานุกรมหรืออ็อบเจกต์การทำแผนที่อื่นๆ ที่ใช้เก็บแอตทริบิวต์ (เขียนได้) ของออบเจ็กต์

ตัวอย่าง

รหัสต่อไปนี้แสดงวิธีการทำงานของ __dict__

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__': <attribute '__dict__' of 'MyClass' objects>, '__weakref__': <attribute '__weakref__' of 'MyClass' objects>, '__doc__': None, '__init__': <function __init__ at 0x0000000004E55CF8>}
{'i_var': 2}
{'i_var': 3}