Examples of the use of @property adorners in Python programming

Source: Internet
Author: User
Value and Assignment

Class actress ():  def __init__ (self):    self.name = ' tianxin '    self.age = 5


There are two member variables in class actress name and age. Outside of the operation of the class's member variables, mainly including the value and assignment. The simple value operation is X=object.var, and the simple assignment operation is object.var=value.

>>> actress = actress () >>> actress.name  #取值操作 ' tianxin ' >>> actress.age    #取值操作20 >>> actress.name = ' NoName '   #赋值操作 >>> actress.name ' NoName '

Using Getter and Setter
These simple values and assignment operations, in some cases, do not meet the requirements. For example, if you want to limit the age range of the actress, then only using the simple assignment above will not satisfy the requirements. Getter and setter implement such a requirement.

Class actress ():  def __init__ (self):    self._name = ' tianxin '    self._age = +  def getage (self):    return self._age  def setage (self, age):    if age >:      raise valueerror    self._age = Age

Calling the Setage function enables you to limit the range of variable _age to less than 30.

>>> actress = actress () >>> actress.setage >>> actress.getage () 28>>> Actress.setage (ValueError)

Use property
The property is defined as:
Where Fget is a value function, Fset is an assignment function, and Fdel is a delete function. The use of the property also implements the above-mentioned restriction on the value of member variables.

Class actress ():  def __init__ (self):    self._name = ' tianxin '    self._age = +  def getage (self):    return self._age  def setage (self, age):    if age >:      raise valueerror    self._age = Age   age= Property (Getage, Setage, None, ' age ')

After the definition above, you can manipulate age as simple as a value and an assignment operation. Like what

>>> actress = actress () >>> actress.age20>>> actress.age = 18>>> Actress.age = 55ValueError

Using @property
The definition of the above class can also be implemented using @property.

Class actress ():  def __init__ (self):    self._name = ' tianxin '    self._age =  @property  def ):    return self._age  @age. Setter  def Age:    if >:      raise ValueError    self._ Age = Age

Examples of Use:

>>> actress = actress () >>> actress.age20>>> actress.age = 18>>> Actress.age = 45ValueError

The difference between using property in Python2 and Python3
The above Property example is valid in a Python3 environment. In Python2, when a property is used, the class definition needs to inherit object. Otherwise, the property's assignment operation is not available.

Python2 the right way to use the property:

Class actress (object):      #差别在这里  def __init__ (self):    self._name = ' tianxin '    self._age =  @ Property  def Age (self):    return self._age  @age. Setter  def-age:    if >:      Raise ValueError    Self._age = Age   def setName (self, name):    self._name = name  def getName (self):    return self._name  def delname (self):    print (' Goodbye ... ')    del self._name  name = Property ( GetName, SetName, Delname, ' Name property ')

Example: Fast code refactoring
Once upon a while, Python programmer Alice was going to create a class that represented money. Her first form of implementation is probably the following:

# The first version of the money class in dollar-based currencies:  def __init__ (self, dollars, cents):    self.dollars = Dollars    self.cents = Cents    # There are other ways we don't have to ignore

This class was later packaged into a Python library and slowly used by many different applications. For example, in another team, Python programmer Bob uses the Money class like this:

Money = Money (+) message = "I have {:d} dollars and {:d} cents." Print (Message.format (Money.dollars, money.cents)) # "I have dollars and cents." Money.dollars + = 2money.cents + = 20print (Message.format (Money.dollars, money.cents)) # "I have dollars and a cents."

This is not a mistake, but there is a problem with the maintainability of the code. Did you find it?

Months or years later. Alice wants to refactor the internal implementation of the money class, not to record dollars and cents, but just to record cents, because doing so can make some operations much easier. Here are some of the changes she would probably make:

# The second version of the Money Class class money:  def __init__ (self, dollars, cents):    self.total_cents = dollars * + cents

This change has a consequence: every line of code that references the Money class must be adjusted. Sometimes it's lucky that you're the maintainer of all this code, and you just need to refactor directly. But Alice's situation is not so good; many teams have reused her code. As a result, she needs to reconcile their code base with their own modifications, perhaps even through a particularly painful and lengthy formal deprecation process (deprecation processes).

Fortunately, Alice knows a better solution to avoid this troubling situation: Using Python's built-in property decorator. @property general application on Python methods, you can effectively turn property access (attribute access) into a method call. For example, put the money class aside for a while, assuming there is a person class (class) that represents humanity:

Class Person:  def __init__ (self, First, last):    Self.first = First    self.last = Last  @property  def Full_name (self):    return ' {} {} '. Format (Self.first, Self.last)

The code style is different because the previous tool has a problem. -earlgrey

Please note the Full_name method. In addition to decorating the @property above the DEF statement, there is no difference in the declaration of the method. However, this changes the way the person object works:

>>> buddy = person (' Jonathan ', ' Doe ') >>> buddy.full_name ' Jonathan Doe '

We found that although full_name is defined as a method, it can be accessed through variable properties. There is no () operator in the last line of code; I did not call the Full_name method. What we do, we can say, is to create some kind of dynamic property.

Back to the Money class in this article, Alice made the following modifications to it:

# Money Class Final version class Money:  def __init__ (self, dollars, cents):    self.total_cents = dollars * + Cents  # Gette R and setter for dollars  ... @property  def dollars (self):    return self.total_cents//;  @dollars. Setter  def dollars (self, new_dollars):    self.total_cents = * New_dollars + self.cents # and the    g Etter and setter for cents.  @property  def cents (self):    return self.total_cents%;  @cents. Setter  def cents (self, new_cents):    self.total_cents = + Self.dollars + new_cents

In addition to the getter that defines the dollars property using the @property adorner, Alice also uses @dollars.setter to create a setter. Alice also treated the cents ' property similarly.

So now, what are the corresponding changes to Bob's code? There's no need to change!

# His code doesn't change at all, but it can call the money class normally. Money = Money (+) message = "I have {:d} dollars and {:d} cents." Print (Message.format (Money.dollars, money.cents)) # "I have dollars and cents." Money.dollars + = 2money.cents + = 20print (Message.format (Money.dollars, money.cents)) # "I have dollars and a cents." # There's no problem with code logic. Money.cents + = 112print (Message.format (Money.dollars, money.cents)) # "I have the dollars and cents."

In fact, all code that uses the Money class does not need to be modified. Bob doesn't know or doesn't care if Alice removes the dollars and cents properties in the class: his code is still as normal as before. The only code that has been modified is the money class itself.

Because of the way the adorner is handled in Python, you can freely use simple properties in the class. If the class you write changes the way you manage the state, you can confidently modify the class (and only this class) through the @property adorner. This is a way to win! Conversely, in languages such as Java, programmers must proactively define methods for accessing properties (such as Getdollars or setcents).

Finally, you should be prompted: This approach is most important for code that is reused by other programmers and teams. Suppose you just create a money-like class in your own maintenance application, and if you change the money's interface, you just need to refactor your own code. In this case, you do not need to use the @property adorner as stated above.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.