# encoding: utf-8 # @file: property.py # @software: PyCharm # @time: 2022/8/9 23:40 # @desc: 方法变成属性调用 """ 装饰器(decorator)可以给函数动态加上功能,对于类的方法,装饰器一样起作用。 Python内置的@property装饰器就是负责把一个方法变成属性调用的: @property:把一个getter方法xxx(无入参)变成属性 @xxx.setter:负责把一个setter方法(有入参)变成属性赋值 """ class Screen(object): # 读属性 @property def width(self): return self.value_width # 写属性 @width.setter def width(self, value): self.value_width = value @property def height(self): return self.value_height @height.setter def height(self, value): self.value_height = value @property def resolution(self): return self.value_height * self.value_width if __name__ == '__main__': s = Screen() # 方法s.width()只能以属性来赋值 s.width = 3 s.height = 4 # 方法s.width()只能能属性来调用了 print(s.width, '---', s.height) assert s.resolution == 1, '错误,3 * 4 != 1' ####################################################### # 3 --- 4 # Traceback (most recent call last): # File "D:studypri_testproperty.py", line 45, in# assert s.resolution == 1, '错误,3 * 4 != 1' # AssertionError: 错误,3 * 4 != 1