Python_getter and setter methods

When a property assignment, using examples. Mode attribute = attribute value is clearly the property exposed, and can not be limited inspection of the property value, java provides a setter and getter method, then python is how to do it?

Property assignment method

When bound property, if we go directly to the property exposed, although it is very simple to write, however, no way to check the parameters that you can easily change the results:


13717038-3f7de742bba52f87.png

The above assignment is clearly inconsistent with the actual situation, in order to limit the scope of score, you can set the score by a set_score () method, and then to get results by a get_score (), so, in set_score () method where you can check the parameters:


13717038-8781c64c7040b4a6.png

Now, for any instance of Student operation can not arbitrarily set the score:


13717038-c7cf3cacc5976f7e.png

However, the above method invocation and slightly complicated, not directly with the property so straightforward.

There is no check both parameters, and variables can be accessed in a similar class attribute such a simple way? For the pursuit of the perfect Python programmers, it is necessary to do!

Remember decorator (secorator) can add functionality to function? For the method of the class, its role as the decorator. Python's built @property decorator is responsible for the property to become a method call:


13717038-ad3e004ec794b3c1.png

@property implementation is more complex, let's look at how to use. To become a property getter method, only need to add @property on it at this time, @ property itself has created another decorator @ score.setter, is responsible for assigning attributes to become a setter method, so we It has a controllable operating properties:


13717038-8ec5bbe735dfd2ec.png

Note that this magical @property, for instance, when we are operating, we know that this property is probably not directly exposed, but through getter and setter methods to achieve.

You can also define the read-only attribute, define only getter method, does not define a setter method is a read-only property:

13717038-5623576431ec8f68.png

The above is a read-write property birth, and age is a read-only property, because the age and birth can be calculated from the current time.

summary

@property widely used in the definition of class, allowing the caller to write a short code, while ensuring the necessary checks on the parameters, so that the program is running reduces the possibility of error.

Guess you like

Origin blog.csdn.net/weixin_34347651/article/details/91001256