classPerson:def__init__(self, name, age):
self._name = name
self._age = age
@propertydefname(self):return self._name
@name.setterdefname(self, value):ifnotisinstance(value,str):raise ValueError("姓名必须是字符串类型")
self._name = value
@propertydefage(self):return self._age
@age.setterdefage(self, value):ifnotisinstance(value,int):raise ValueError("年龄必须是整数类型")if value <0:raise ValueError("年龄不能为负数")
self._age = value
p = Person("张三",25)print(p.name)# 输出:张三print(p.age)# 输出:25
p.name ="李四"
p.age =30print(p.name)# 输出:李四print(p.age)# 输出:30
四、小结
setter属性通常需要和property一起使用,否则会提示错误。
property属性列表
defdeleter(self,*args,**kwargs):# real signature unknown""" Descriptor to change the deleter on a property. """passdefgetter(self,*args,**kwargs):# real signature unknown""" Descriptor to change the getter on a property. """passdefsetter(self,*args,**kwargs):# real signature unknown""" Descriptor to change the setter on a property. """pass