Python中使用@property来定义属性

@spiritree  October 3, 2016

上一篇提到装饰器(Decorator)可以在不改变函数的前提下给函数增加功能,Python中内置的装饰器@property就是把一个方法变成属性调用的。

利用@property给一个Screen对象加上widthheight属性,以及一个只读属性resolution

class Screen(object):

    @property
    def width(self):
        return self._width

    @width.setter
    def width(self, value):
        if not isinstance(value, int):
            raise ValueError('width must be interger!')
        if value < 0:
            raise ValueError("Input error. The input width is less than 0!")
        else:
            self._width = value

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

    @height.setter
    def height(self, value):
        if not isinstance(value, int):
            raise ValueError('width must be interger!')
        if value < 0:
            raise ValueError("Input error. The input width is less than 0!")
        else:
            self._height = value

    @property
    def resolution(self):
        return self._width * self._height

s = Screen()
s.width = 1024
s.height = 768
print(s.resolution)
assert s.resolution == 786432, '1024 * 768 = %d ?' % s.resolution

添加新评论