python Of @property yes python A decorative device for , It is used to modify the method .python @property Decorators enable a method to be used like an attribute . besides , There are also several usage scenarios , This article will describe these techniques .
First, let's look at the classification of attributes :
General in class attributes refer to attributes defined as the same storage unit as the class , Class access . When a class is instantiated as an object , Class variables will be added to the object as copies , The property accessed by the object is a copy . This copy is changeable after modification .
Verification code
class Stranger(object):
name = 'class name' # Class binding properties
def __init__(self, gender=None ):
self.gender = gender # Object binding properties
self.name = 'new name' # Properties in object , A copy of the same name as a class attribute
stan = Stranger('male')
print(1,stan.gender)
stan.gender = 'famel'
print(2,stan.gender)
print(3 stan.name)
print( 4, Stranger.name)
result :
1 male
2 famel
3 new name
4 class name
All use self Properties defined , Are object binding properties ,
class Stranger(object):
def __init__(self, gender=None ):
self.gender = gender
stan = Stranger('roma')
print(stan.gender)
stan.gender = 'Paras'
print(stan.gender)
result :
roma
Paras
Be careful : In fact, the instantiated object , You can also define attributes , External can also call .
python There is no compilation qualification for the private property of , Knowledge is underlined with a single line _ start , Mark this property as private , But external access is also free ( Not enough private ). The other is double underlined __ The properties of the beginning , Can be converted to class attribute access
python Of @property yes python A decorative device for , It is used to modify the method .python @property Decorators enable a method to be used like an attribute , You don't need to bring... When calling ()
Next we will learn when we need to use it , And in what scenarios need to use it and how to use it reasonably .
python Class @property Decorator , The matching methods are :
Match .
When converting an attribute to a method , We'd better add one @property
Decorator to solve this problem . Add a to the method definition @property
Decorator , You can do this without changing the original invocation method , To change an attribute to a method .
class Goods():
def __init__(self,unit_price,weight):
self.unit_price = unit_price
self.weight = weight
@property
def price(self):
return self.unit_price * self.weight
lemons = Goods(7,4)
print(lemons.price)
28
In this paper ,price Is the method , Now turn the method into an attribute call . Pay attention to this technique , Know that there is no in the original class definition price This attribute , This is a temporary result . Similar to excel Tabular “ Calculated items ”.
For some properties , Not directly accessible . there “ direct ” Namely “ Unconditional ” It means ; And conditional access , You need a decorator @property, The following example is a double decorator @property and @age.setter coordination , Yes _age Examples of conditional isolation :
class Stranger(object):
def __init__(self, gender=None, age=None, job=None):
self.gender = gender
self._age = age # The member properties here _age Need to work with member methods age() Differentiate
self.jobb = job
# Read age
@property # Achieve one age dependent getter Method
def age(self):
return self._age
# Set up age
@age.setter # Achieve one age dependent setter Method
def age(self, value):
if isinstance(value, int):
self._age = value
else:
raise ValueError("'int' type need")
if __name__ == "__main__":
# Create a “ sister ”
meizi = Stranger()
meizi.age = 18 # When using, pay attention to .age, No ._age
print(" Age :{age}".format(age=meizi.age))
matters needing attention :
such as , We entered first_name、last_name We can draw fullname, The following code can realize the attribute acquisition of the full name . Conversely , After modifying the full name , How to combine the first_name、last_name Modify synchronously ?. In the following @fullname.setter Is to solve such problems .
class Person():
def __init__(self, first_name, last_name):
self.first = first_name
self.last = last_name
@property
def fullname(self):
return self.first + ' ' + self.last
@fullname.setter
def fullname(self, name):
first_name, last_name = name.split()
self.first = first_name
self.last = last_name
def email(self):
return '{}.{}@email.com'.format(self.first, self.last)
person = Person('zhang', 'san')
print(person.fullname)
print(person.last)
print(person.first)
person.fullname = 'li si'
print(person.fullname)
print(person.last)
print(person.first)
deleter
Method and setter
The method is similar to , When we need to delete an attribute , We will use deleter
Method .
You can define setter
Method to define a setter
Method , Use the same method name , And add... To the method @{methodname}.deleter
Decorator .
class Person():
def __init__(self, first_name, last_name):
self.first = first_name
self.last = last_name
@property
def fullname(self):
return self.first + ' ' + self.last
@fullname.setter
def fullname(self, name):
first_name, last_name = name.split()
self.first = first_name
self.last = last_name
@fullname.deleter
def fullname(self):
self.first = None
self.last = None
def email(self):
return '{}.{}@email.com'.format(self.first, self.last)
person = Person('zhang', 'san')
print(person.fullname)
print(person.last)
print(person.first)
del person.fullname
print(person.last)
print(person.first)
Using this function, you can turn a method directly into an attribute , And @property similar .
Use property Code example of :
class Stranger(object):
def __init__(self, gender=None, age=None, job=None):
self.gender = gender
self._age = age
self.jobb = job
# Set up _age
def set_age(self, age):
if isinstance(age, int):
self._age = age
else:
raise ValueError("'int' type need")
# Read _age
def get_age(self):
return self._age
# So that the instantiated object can take advantage of .age Way to visit
age = property(get_age, set_age)
if __name__ == "__main__":
# Create a “ sister ”
meizi = Stranger()
meizi.age = 18
print(" Age :{age}".format(age=meizi.age))
# Output :
# Age :18