Suppose a class is defined: C, the class must inherit from the object class and have a private variable _x
Copy the Code code as follows:
Class C:
def __init__ (self):
Self.__x=none
1. The first method of using attributes is now introduced:
Define three functions in the class to use as assignment, value, and delete variables (the expression may not be clear here, see 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 property function prototype is property (Fget=none,fset=none,fdel=none,doc=none), so the corresponding function can be defined according to its own needs.
Now that the X attribute in this class has been defined, we can first define an instance of C c=c (), then assign the value c.x=100, y=c.x, delete: Del c.x. Isn't it simple? Take a look at the second method
2. See the second method (new in 2.6)
First define a Class C:
Copy the Code code as follows:
Class C:
def __init__ (self):
Self.__x=none
The properties are now defined as follows
@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 three function names of the same attribute must be the same.