@property是python的一种装饰器,是用来修饰方法的。
作用:
使用@property装饰器来创建只读属性,@property装饰器会将方法转换为相同名称的只读属性,可以与所定义的属性配合使用,这样可以防止属性被修改。
例子:
class Server(): def get_name(self): return 'a' @property def start(self): return 'a' obj = Server() 不加property,调用方法要加括号 print(obj.get_name()) 加property,调用方法不需要加括号 print(obj.start)
property实际用途:由于python进行属性的定义时,没办法设置私有属性,因此要通过@property的方法来进行设置。
这样可以隐藏属性名,让用户进行使用的时候无法随意修改
例子:
class Server(): def __init__(self): self.parameter = 'a' def get_name(self): return 'a' @property def start(self): return self.parameter obj = Server() print(obj.get_name()) print(obj.start) #隐藏了parameter属性名