Discuss / Python / property作业

property作业

Topic source

烈可烈

#1 Created at ... [Delete] [Delete and Lock User]

`

class Screen(object):
    @property
    def width(self):
        return self._width  # 加下划线是为了避免程序员混乱,是调属性,还是调方法(就算不加下划线,编译器也会避免递归)
    @width.setter
    def width(self, value):
        if value <= 0:
            raise ValueError()
        self._width = value

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

    @height.setter
    def height(self, value):
        if value <= 0:
            raise ValueError()
        self._height = value

    @property
    def resolution(self):
        try:
            return self._width * self._height
        except AttributeError:
            return 0

`

表示不加下划线会报循环递归错误。 宽高没有加下划线,无法分清调用的是方法还是变量,致使报超过递归深度异常:

#coding:utf-8
class Screen(object):
    @property
    def width(self):
        return self.width

    @width.setter
    def width(self, value):
        self.width = value

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

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

    @property
    def resolution(self):
        return self.width * self.height

if __name__ == '__main__':
    s = Screen()
    s.width = 10
    s.height = 20
    print(s.resolution)

报错如下:

Traceback (most recent call last):
  File "Screen.py", line 25, in <module>
    s.width = 10
  File "Screen.py", line 9, in width
    self.width = value
  File "Screen.py", line 9, in width
    self.width = value
  File "Screen.py", line 9, in width
    self.width = value
  [Previous line repeated 495 more times]
RecursionError: maximum recursion depth exceeded

  • 1

Reply