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

วิธีตรวจสอบว่า Class Attribute ถูกนิยามหรือสืบทอดใน Python

โค้ดด้านล่างแสดงว่าแอตทริบิวต์ 'foo' ถูกนิยามหรือสืบทอดในคลาส A และ B

ตัวอย่าง

class A:
    foo = 1

class B(A):
    pass

print(A.__dict__)  # foo อยู่ใน __dict__ ของ A -> defined in A
print(hasattr(A, 'foo'))  # True (defined)

print(B.__dict__)  # foo ไม่อยู่ใน __dict__ ของ B -> not defined in B
print(hasattr(B, 'foo'))  # True (derived/inherited)

ผลลัพธ์

{'__module__': '__main__', 'foo': 1, '__doc__': None}
True
{'__module__': '__main__', '__doc__': None}
True

ใช้ __dict__ ตรวจสอบว่านิยามในคลาสนั้นจริงหรือสืบทอดมา (hasattr คืน True ทั้งคู่)