@property and @ xxx.setter usage

Class and @ xxx.setter @property described method.

Simply put, @ property is the function (method) will be defined as a property of the object to use, you do not need to call a function like that to call, and @ xxx.setter is set to the value of such a function @xxx,

It is that you can make changes as a function of the value of xxx with @ xxx.setter, in the name of the function at xxx @ xxx.setter statement can not function the same name.

Property decorator # 
# action: convert a property of the object get method. Is to call the method was changed to call the object
# Conditions: must and attribute names as

# decorator setter methods:
# Role: to convert a set method for the property of the object. A method is invoked instead call the object
# Usage: @ attribute name .setter

class the Person:
DEF __init __ (Self, name):
self._name = name
# decorator will use property name acquisition method of converting properties for acquisition targets
@property
name DEF (Self):
return self._name

# decorator using property name setting method of converting the properties of an object to acquire
@ name.setter
DEF Nam (Self, name):
self._name name =
self.a = 22 is
P = the Person ( 'black')
Print (p.name) # original acquisition p.neame (), now p.name, has a function (method of obtaining the attribute value becomes)
p.nam = 'small gray' original settings p # .name ( 'small gray'), now p.name = 'small gray', corresponding to the direct use of the variable name, the attribute value to change this variable
Print (p.name)



class the Person:
DEF the __init __ (Self, name):
self._name name =
@Property
DEF name (Self):
A = 100
return self._name, A
@ name.setter
DEF name (Self, name) : # name is a list containing two elements
self._name = name [0] # value is assigned the first element self._name
a name = [. 1] # is assigned a second value, but in the implementation a name () function when there will be a = 100, so it does not change the variables
p = Person ( 'black')
Print (p.name)
p.name = [88,99] is performed as # a = 100 Therefore performed when a = name [1], the output value will not change
Print (p.name)

class the Person:
DEF the __init __ (Self, name, BB):
self._name name =
self.a = BB
# use property decorative the method name is converted to the acquired object property acquiring
@property
name DEF (Self):

return self._name, self.a
# decorator using property name setting method of converting the properties of an object to acquire
@ name.setter
DEF name (Self, name):
self._name = name [0]
Self name = II.A [. 1]
P = the Person ( 'black', 100)
Print (p.name) # original acquisition p.name (), now p.name, has a function (method of obtaining the attribute value becomes)
p.name = [88, 'Xiaohui'] # @property plurality of attributes output
print (p.name)

 

 





Guess you like

Origin www.cnblogs.com/tangjunjun/p/12078686.html