Hướng dẫn dùng python __getattr__ python
Description¶Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for self). Syntax¶object. __getattr__(self, name) selfRequired. Instance of the class, passed automatically on call.nameRequired. The name of the attribute.Example¶>>> class Frob: ... def __init__(self, bamf): ... self.bamf = bamf ... def __getattr__(self, name): ... return 'Frob does not have `{}` attribute.'.format(str(name)) ... >>> f = Frob("bamf") >>> f.bar 'Frob does not have `bar` attribute.' >>> f.bamf 'bamf' Hãy xem một số ví dụ đơn giản về cả hai
__getattr__Python sẽ gọi
Bây giờ lớp học của tôi Đếm có
__getattribute__Bây giờ hãy xem Bất cứ khi nào ai đó cố gắng truy cập các thuộc tính của tôi bắt đầu bằng chuỗi con
trăn 'cur', chuỗi
Quan trọng: Để tránh đệ quy vô hạn trong QUAN TRỌNGNếu lớp của bạn chứa cả phương thức ma thuật getattr và getattribution thì
93 hữu ích 1 bình luận chia sẻ |