Discuss / Python / 使用@property把类方法当成属性调用

使用@property把类方法当成属性调用

Topic source
class Screen(object):

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

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

    @width.setter
    def width(self, v):
        self.__isValidInput(v)
        self.__width = v

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

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

    def __isValidInput(self, v):
        if not isinstance(v, (int, float)) or v <= 0:
            raise ValueError('请输入正数!')

  • 1

Reply