Computer >> Máy Tính >  >> Lập trình >> Python

Làm cách nào để kiểm tra xem thuộc tính lớp đã được định nghĩa hoặc có nguồn gốc trong lớp đã cho bằng Python hay chưa?


Đoạn mã dưới đây hiển thị nếu thuộc tính 'foo' được xác định hoặc dẫn xuất trong các lớp A và B.

Ví dụ

class A:
    foo = 1
class B(A):
    pass
print A.__dict__
#We see that the attribute foo is there in __dict__ of class A. So foo is defined in class A.
print hasattr(A, 'foo')
#We see that class A has the attribute but it is defined.
print B.__dict__
#We see that the attribute foo is not there in __dict__ of class B. So foo is not defined in class B
print hasattr(B, 'foo')
#We see that class B has the attribute but it is derived

Đầu ra

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