Assume that a class is defined: C, which must inherit from the object class and has a private Variable _ x
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:
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 ..