Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Kiểm tra attribute được định nghĩa hay kế thừa trong class Python

Dùng __dict__ của class để kiểm tra attribute có được định nghĩa trực tiếp hay kế thừa.

Ví dụ

class A:
    foo = 1

class B(A):
    pass

print(A.__dict__)   # {'__module__': '__main__', 'foo': 1, '__doc__': None} -> foo có trong __dict__ => defined in A
print(hasattr(A, 'foo'))  # True

print(B.__dict__)   # {'__module__': '__main__', '__doc__': None} -> foo KHÔNG có => not defined in B
print(hasattr(B, 'foo'))  # True (kế thừa từ A)

Kết quả

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

Tóm tắt:

  • attr in Class.__dict__ → defined trực tiếp trong class
  • hasattr(Class, 'attr') → có attribute (defined hoặc inherited)