Tag: MoS arm string value Finish call user Pycha Lin
Class Shuxing (): def __init__ (self, size = Ten): self.size = size def getsize (self): print (' GetSize ') return self.size def setSize (self, value): print (' setSize ') self.size = value def delsize (self) : print (' delsize ') del self.size x = Property (GetSize, SetSize, delsize) print (' 1 ', sx=shuxing #获取x, execute the GetSize method sx.x=1000 #设置x, execute the SetSize method print (' 2 ', sx.x) #获取x, execute the GetSize method del sx.x # Delete x, Executes the Delsize method print (' 3 ', sx.size) # gets X, executes the GetSize method, but at this point the size is deleted, so an error is made
Results:
getsize1Traceback (most recent): Setsizegetsize"d:/pycharmprojects /flask_demo/a.py" in <module>2delsize print(' 3 ' 'shuxing'size'1
The three functions in the property () function correspond to the method of getting the attribute, the method of setting the property, and the method of deleting the property , so that the external object can get, set or delete the property by accessing X.
When you need to change the name of the GetSize, setsize, or delsize functions in the previous example, if these methods are called by the user as an interface, then it is troublesome for the user to modify the name of the method that they call, and after using the Proprty (), the user does not need to worry about the problem.
More about the properties of the built-in methods are:
Hasattr (): Determines whether an object has a property with the specified name, the first argument is an object, and the second argument is a string (property name);
GetAttr (): Gets the value of the specified property in the object, if the property does not exist, returns the specified prompt string, the first argument is the object, the second argument is a string (property name), and the third argument is a string (the prompt to access the property does not exist);
SetAttr (): Sets the value of the property specified in the object and, if the property does not exist, automatically adds the property to the object, assigns a value, the first argument is the object, the second argument string (property name), and the third parameter is the value that corresponds to the property that needs to be set;
Delattr (): Deletes the specified property in the object, the first parameter is the object, and the second parameter needs to be removed for the name of the specified property.
Python built-in function property () Usage instance