Python基础学习(使用@property)
我们可以通过设置私有变量将类中的属性隐藏起来,然后通过方法对其进行修改和参数检查。但这样做有时会显得比较冗余,可以使用@property将方法变为属性来进行调用。
例如:
class Student(object):
@property
def score(self):
return self.__score
@score.setter
def score(self, value):
if not isinstance(value, int):
raise ValueError('score must be an integer')
if value < 0 or value > 100:
raise ValueError('score must be 0 ~ 100!')
self.__score = value
student_A = Student()
student_A.score = 50
print(student_A.score)
50
student_A.score = 10000
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-8-8c771a8ad78f> in <module>
----> 1 student_A.score = 10000
<ipython-input-5-e77234502a3f> in score(self, value)
10 raise ValueError('score must be an integer')
11 if value < 0 or value > 100:
---> 12 raise ValueError('score must be 0 ~ 100!')
13 self.__score = value
ValueError: score must be 0 ~ 100!
Practice:利用@property给一个Screen对象加上width和height属性,以及一个只读属性resolution
class Screen(object):
@property
def width(self):
return self.__width
@width.setter
def width(self, value):
if not isinstance(value, int):
print('Please input a integer!')
if value < 0:
print('Please input a positive number')
self.__width = value
@property
def height(self):
return self.__height
@height.setter
def height(self, value):
if not isinstance(value, int):
print('Please input a integer!')
if value < 0:
print('Please input a positive number')
self.__height = value
#设置只读属性,即不写它的设置方法
@property
def resolution(self):
return self.__width * self.__height
screen_A = Screen()
screen_A.width = 10
print(screen_A.width)
10
screen_A.height = 50
print(screen_A.height)
50
print(screen_A.resolution)
500
screen_A.resolution = 100
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-14-c15e19203741> in <module>
----> 1 screen_A.resolution = 100
AttributeError: can't set attribute