请利用@property
给一个Screen
对象加上width
和height
属性,以及一个只读属性resolution
:
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
1、当执行如下语句:
s = Screen()
s.width
Python会在s的
__dict__
中查找key值为width的value,因此
s.width
在内部就变成了
s.__dict__['width']
2、下划线‘_’的理解:下划线在Python中表明该变量是private类型
3、不加下换线报错的问题:RecursionError: maximum recursion depth exceeded
@property
def height(self):
return self.height
参考链接:https://www.programiz.com/python-programming/property
该函数会递归的调用自己,造成死循环