1.1 Use@property
When you enter your score score , you need to check this parameter.
>>> class Student (object):
... def get_score (self):
... return Self.__score
... def set_score (self, value):
... if not isinstance (value, int):
... raise ValueError (' score must beinteger ')
... if value < 0 or value > 100:
... raise ValueError (' score Mustbetween 0 and 100. ')
... self.__score = value
...
>>> s = Student ()
>>> S.set_score (60)
>>> S.get_score ()
60
>>> S.set_score (999)
Traceback (most recent):
File "<stdin>", line 1, in <module>
File "<stdin>", line 8, in Set_score
Valueerror:score must between 0 and 100.
Is there any way to access and modify the variables of a class in such an easy manner as to check parameters and use similar properties?
Python's built-in @property Decorator is responsible for turning a method into a property.
>>> class Student (object):
... @property
... def score(self):--score can be understood as a property
... return self.__score-- return property
... @score. Setter
... def score(self, value):--score can be understood as a property
... if not isinstance (value, int):
... raise ValueError (' score must be aninteger. ')
... if value < 0 or value > 100:
... raise ValueError (' score Mustbetween 0 and 100. ')
... self.__score = value-- Modify Properties
...
>>> s = Student ()
>>> S.score =-- Modify the attribute, here is no longer the calling method, thescore property is readable and writable
>>> S.score
60
>>> S.score =-1
Traceback (most recent):
File "<stdin>", line 1, in <module>
File "<stdin>", line ten, in score
Valueerror:score must between 0 and 100.
define read -only properties -Define getter methods only, do not define setter is read-only
>>> class Student (object):
... @property
... def birth (self):
... return Self._birth
... @birth. Setter
... def birth (self, value):
... Self._birth = value--birth readable writable
... @property
... def age (self):
... return 2016-self._birth--age Read Only
...
>>> s = Student ()
>>> S.birth = 1992
>>> S.birth
1992
>>> S.age
24
This article is from the "90SirDB" blog, be sure to keep this source http://90sirdb.blog.51cto.com/8713279/1826208
Python advanced programming for objects--using @property