Python Property has two usage methods: pythonproperty
Assume that a class is defined: C, which must inherit from the object class and has a private Variable _ x
Copy codeThe Code is as follows:
Class C:
Def _ init _ (self ):
Self. _ x = None
1. Now we will introduce the first method to use attributes:
Define three functions in this class for assignment, value, and deletion (the expression may not be clear here, please refer to the example)
Def getx (self ):
Return self. _ x
Def setx (self, value ):
Self. _ x = value
Def delx (self ):
Del self. _ x
X = property (getx, setx, delx ,'')
The prototype of the property function is property (fget = None, fset = None, fdel = None, doc = None), So define the corresponding function as needed.
Now the x attribute in this class has been defined. We can first define a C instance c = C () and then assign the value c. x = 100, value: y = c. x, delete: del c. x. Is it easy? See method 2
2. See the second method (added in 2.6)
First define a class C:
Copy codeThe Code is as follows:
Class C:
Def _ init _ (self ):
Self. _ x = None
The attributes are defined below.
@ Property
Def x (self ):
Return self. _ x
@ X. setter
Def x (self, value ):
Self. _ x = value
@ X. deleter
Def x (self ):
Del self. _ x
The names of the three functions in the same attribute must be the same ..