程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python knowledge: what is the use of decorator @property?

編輯:Python

One 、 summary

        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 .

Two 、 Conventions on attributes

First, let's look at the classification of attributes :

2.1 Class binding properties

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

2.2 Object binding properties

All use self Properties defined , Are object binding properties ,

  • When calling internally, you need to add self.
  • For external calls, use instance_name.property_name Visit
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 . 

2.3 Private property  

        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

  • Underline _ start : Just tell others that this is a private property , Changes can still be accessed externally
  • Double underline __ start : The outside cannot pass through instancename.propertyname To access or change , Actually turn it into _classname__propertyname

3、 ... and 、 application @property Decorator

        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 :

  • setter() 
  • get() 
  • set()

Match .
 

3.1 Turn an attribute into a method

         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 ”.

3.2 Privatize certain properties

         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 :

  • Property names and method names must be distinguished , Otherwise, it will enter the dead circle (self._age,def age())
  • When an instantiated object uses properties , Not calling properties (meizi._age), Instead, use the method name (meizi.age)
  • @property In fact, it is realized getter function ; @xxx.setter What we achieve is setter function ; One more @xxx.deleter Realize the deletion function
  • When defining methods @property Must be in @xxx.setter Before , And the names of the two modified methods are the same (age())
  • If only @property( And it didn't happen @xxx.setter), Then the attribute is Read-only property

3.3 Relevance modification

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)

3.4 Delete attribute's 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)

 

Four 、property() The principle of function

Using this function, you can turn a method directly into an attribute , And @property similar .

  • The function interface :property(fget=None, fset=None, fdel=None, doc=None)

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


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved