The example explains the @ property modifier usage in Python programming, and python @ property

Source: Internet
Author: User

The example explains the @ property modifier usage in Python programming, and python @ property

Value and value assignment

class Actress():  def __init__(self):    self.name = 'TianXin'    self.age = 5


Class Actress has two member variables: name and age. External operations on the member variables of the class mainly include value and value assignment. The simple value operation is x = object. var, and the simple value assignment operation is object. var = value.

>>> Actress = Actress () >>> actress. name # value operation 'tiance'> actress. age # value operation 20 >>> actress. name = 'noname' # value assignment >>> actress. name 'noname'

Use Getter and Setter
The preceding simple value and value assignment operations cannot meet the requirements in some cases. For example, if you want to limit the age range of Actress, you cannot use the simple assignment operation described above. Getter and setter implement this requirement.

class Actress():  def __init__(self):    self._name = 'TianXin'    self._age = 20  def getAge(self):    return self._age  def setAge(self, age):    if age > 30:      raise ValueError    self._age = age

You can call the setAge function to set the value range of Variable _ age to less than 30.

>>> actress = Actress()>>> actress.setAge(28)>>> actress.getAge()28>>> actress.setAge(35)ValueError

Use property
Property is defined:
Fget is the value function, fset is the value function, and fdel is the delete function. Using property also limits the value of member variables.

class Actress():  def __init__(self):    self._name = 'TianXin'    self._age = 20  def getAge(self):    return self._age  def setAge(self, age):    if age > 30:      raise ValueError    self._age = age   age=property(getAge, setAge, None, 'age property')

After the above definition, you can operate on the age just like a simple value and a value assignment operation. For example,

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

Use @ property
@ Property can also be used to define the above class.

class Actress():  def __init__(self):    self._name = 'TianXin'    self._age = 20  @property  def age(self):    return self._age  @age.setter  def age(self, age):    if age > 30:      raise ValueError    self._age = age

Example:

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

Difference between using property in Python2 and Python3
The preceding property example is valid in the Python3 environment. In Python2, when using property, the class must inherit the object during definition. Otherwise, the property assignment operation is unavailable.

The correct usage of property in Python2:

Class Actress (object): # difference here def _ init _ (self): self. _ name = 'tiance' self. _ age = 20 @ property def age (self): return self. _ age @ age. setter def age (self, age): if age> 30: 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 = property (getName, setName, delName, 'name properties ')
Instance: quick code refactoring
In the past, Alice, a Python programmer, was planning to create a class that represents money. Her first implementation form is probably as follows:
# Class Money: def _ init _ (self, dollars, cents): self. dollars = dollars self. cents = cents # There are other methods that we don't need to worry about for the moment.

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

money = Money(27, 12)message = "I have {:d} dollars and {:d} cents."print(message.format(money.dollars, money.cents))# "I have 27 dollars and 12 cents."money.dollars += 2money.cents += 20print(message.format(money.dollars, money.cents))# "I have 29 dollars and 32 cents."

There is nothing wrong with this method, but there is a problem of code maintainability. Have you found out?

Months or years later. Alice wants to refactor the internal implementation of the Money class, instead of recording the dollar and cent, but only recording the cent, because doing so can make some operations much easier. Below are some of the changes she may make:

# The second version of the Money class: class Money: def _ init _ (self, dollars, cents): self. total_cents = dollars * 100 + cents

This modification has the consequence that every line of code that references the Money class must be adjusted. Sometimes you are lucky to be the maintainer of all these codes. You just need to refactor them on your own. But Alice's situation is not that good; many teams have reused her code. Therefore, she needs to coordinate their code library to stay consistent with her own modifications, and perhaps even go through a particularly painful and long deprecation process ).

Fortunately, Alice knows a better solution to avoid this headache: Use the Python built-in property decorator. @ Property is generally applied to Python methods. attribute access can be effectively converted into method call ). For example, if you temporarily throw the Money class to one side, assume that there is a Person class that represents humans ):

class Person:  def __init__(self, first, last):    self.first = first    self.last = last  @property  def full_name(self):    return '{} {}'.format(self.first, self.last)

Different Code styles are caused by problems with previous tools. -EarlGrey

Note the full_name method. In addition to the @ property decoration above the def statement, the declaration of this method is nothing different. 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 attributes. There is no () operator in the last line of code; I didn't call the full_name method. What we do is to create a dynamic attribute.

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

# Final version of the Money class Money: def _ init _ (self, dollars, cents): self. total_cents = dollars * 100 + cents # Getter and setter for dollars... @ property def dollars (self): return self. total_cents // 100; @ dollars. setter def dollars (self, new_dollars): self. total_cents = 100 * new_dollars + self. cents # And the getter and setter for cents. @ property def cents (self): return self. total_cents % 100; @ cents. setter def cents (self, new_cents): self. total_cents = 100 * self. dollars + new_cents

In addition to defining the getter of the dollars attribute using the @ property modifier, Alice also creates a setter using @ dollars. setter. Alice also performs similar processing on the cents attribute.

So now, what changes do Bob's Code make? You don't have to change it!

# His code is completely unchanged, but the Money class can be called normally. Money = Money (27, 12) message = "I have {: d} dollars and {: d} cents. "print (message. format (money. dollars, money. cents) # "I have 27 dollars and 12 cents. "money. dollars + = 2money. cents + = 20 print (message. format (money. dollars, money. cents) # "I have 29 dollars and 32 cents. "# No problem with the code logic. Money. cents + = 112 print (message. format (money. dollars, money. cents) # "I have 30 dollars and 44 cents ."

In fact, all the code that uses the Money class does not need to be modified. Bob doesn't know or doesn't care about Alice's removal of the dollars and cents attributes in the class: His code is still normal as before. The only modified code is the Money class itself.

It is precisely because of the way Python handles decorator that you can freely use simple attributes in the class. If the class you write changes the management state, you can confidently modify the class (and only this class) through the @ property modifier. This is a win-win solution! On the contrary, in Java and other languages, programmers must take the initiative to define methods for accessing attributes (such as getDollars or setCents ).

Finally, I would like to remind you that this method is the most important for the code that is reused by other programmers and teams. Assume that you only create a class similar to Money in your own maintenance application. If you change the Money interface, you only need to refactor your code. In this case, you do not need to use the @ property modifier as mentioned above.

Related Article

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.