This article brings you a detailed introduction (code example) about attribute descriptors in python. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
As a novice, I am constantly reading things and learning knowledge every day. Today I would like to introduce a good thing to you-Attribute descriptor
What is an attribute descriptor?
In fact, any magic function among set__, __get__, __delete implemented in a class is an attribute descriptor.
Next we define an attribute descriptor:
class IntegerField: def __get__(self, instance, owner): pass def __set__(self, instance, value): pass def __delete__(self, instance): pass class User: high= IntField()
__get__: When we call this attribute with a class or instance, the result of the __get__ function will be returned.
__set__: Python calls this function when we use Instance to set the attribute value. There are no restrictions on classes.
__delete__: Python will call this function when we try to delete the attribute using an instance. There are no restrictions on classes.
How to use this thing? Next, I will modify the above code for everyone
class IntegerField: def __get__(self, instance, owner): return self.value def __set__(self, instance, value): if not isinstance(value,numbers.Integral): raise ValueError("请输入一个整数") self.value=value def __delete__(self, instance): pass class User: high=IntegerField() #验证代码 if __name__ == '__main__': user=User() user.high='175' #报错,ValueError:请输入一个整数 User.high=175 #正确执行,不报错
so that we can use attribute descriptors to attach certain logic to the attributes.
In fact, under the attribute descriptor, it is also divided into
1. Data descriptor: implements __set__, __get__
if __name__ == '__main__': user=User() user.high=175 print(user.__dict__) #high是不放入__dict__中的,优先查找数据描述符中的值 user.__dict__["high"]="abc" #这样赋值时可以的,并且可以放入__dict__中 print(user.high) #会报错,因为在调用__get__方法时并没有value属性
2. Non-data: implements __get__ but does not implement __set__
class NonField: def __init__(self, high=170): self.value = high def __get__(self, instance, owner): return self.value class User: high = NonField() if __name__ == '__main__': user = User() user.high = '175' #会放入user.__dict__中 print(user.__dict__)
The above is the detailed content of Detailed introduction to attribute descriptors in python (code example). For more information, please follow other related articles on the PHP Chinese website!