使用@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 between 0 ~ 100!')
        self._score = value。

运行

>>> s = Student()
>>> s.score = 60 # OK,实际转化为s.set_score(60)
>>> s.score # OK,实际转化为s.get_score()
60
>>> s.score = 9999
Traceback (most recent call last):
  ...
ValueError: score must between 0 ~ 100!

 

练习
请利用@property给一个Screen对象加上width和height属性,以及一个只读属性resolution:

# -*- coding: utf-8 -*-

class Screen(object):
    @property
    def width(self):
        return self.__width     #注意这里一定要是私有属性

    @property
    def height(self):
        return self.__height

    @width.setter
    def width(self,value):
        self.__width=value      #注意这里一定要是私有属性

    @height.setter
    def height(self,value):
        self.__height=value

    @property
    def resolution(self):
        return self.__width*self.__height

测试

# 测试:
s = Screen()
s.width = 1024
s.height = 768
print('resolution =', s.resolution)
if s.resolution == 786432:
    print('测试通过!')
else:
    print('测试失败!')

  

 

posted @ 2018-04-30 19:10  Gringer  阅读(624)  评论(0编辑  收藏  举报