In Python, we can intercept all of the object's feature accesses. With this interception idea, we can implement the property method in the old class.
__getattribute__ # called automatically when the attribute name is accessed (can only be used in modern classes) __getattr__ # called automatically when the attribute name is accessed and the object does not have a corresponding attribute __setattr__ # automatically called when attempting to assign a value to an attribute name __delattr__ # automatically called when an attribute name is attempted to be deleted # * Compared to the use of property is a bit complex, but the special method uses very wide
Here is an example:
classDemo5 (object):def __init__(self):Print("This is a constructor") self._value1=None self._value2=Nonedef __setattr__(self, Key, value):Print("try to set the value of the%s property"%(key,))ifKey = ='NewValue': self._value1, Self._value2=valueElse: Print("The property key isn't NewValue, now create or set it through __dict__") self.__dict__[Key] =valuedef __getattr__(self, item):Print("try to get the value of%s"%(item,))ifitem = ='NewValue': returnself._value1, Self._value2Else: Print("The %s Item is not exist"%(item,))#Raise Attributeerror def __delattr__(self, item):ifitem = ='NewValue': Print("Delete the value of NewValue") delself._value1delself._value2Else: Print("Delete other values, the value of name is%s"%Item)if __name__=="__main__": Testdemo=Demo5 ()Print(testdemo.newvalue) Testdemo.newvalue="name","HelloWorld" Print("Print the value of the property:", Testdemo.newvalue)Print(testdemo.notexist)delTestdemo.newvalue
Here's the result:
This is a constructorTryTo set the value of the _value1 propertythe property key is notNewValue, now createorSet it Through__dict__TryTo set the value of the _value2 propertythe property key is notNewValue, now createorSet it Through__dict__Tryto get the value of NewValue (none, none)TryTo set the value of the NewValue propertyTryTo set the value of the _value1 propertythe property key is notNewValue, now createorSet it Through__dict__TryTo set the value of the _value2 propertythe property key is notNewValue, now createorSet it Through__dict__TryTo get the value of NewValue ('Print the value of the property:', ('name','HelloWorld'))TryTo get the value of Notexist the Notexist item is notExistnonedelete The value of newvaluedelete other values, the value name is_value1delete Other values, the value name is_value2
* * In fact, we can see that when using __setatter__, __getatter__,__delatter__ These interfaces will have an impact on other values because this is a generic interface that must be called.
Methods of using property attributes in old Python classes