python中property装饰器
程序员文章站
2022-03-08 08:01:07
property装饰器,用来将一个get方法,转换为对象的属性,添加为property装饰器以后,我们就可以向调用属性一样使用get方法。往往和setter方法装饰器一起使用。class Person : def __init__(self,name='',age=20, sex='man'): self.__name = name # 私有属性 self.__age = age self.__sex = sex @property...
property装饰器,用来将一个get方法,转换为对象的属性,添加为property装饰器以后,我们就可以向调用属性一样使用get方法。往往和setter方法装饰器一起使用。
class Person :
def __init__(self,name='',age=20, sex='man'):
self.__name = name # 私有属性
self.__age = age
self.__sex = sex
@property # property装饰器,用来将一个get方法,转换为对象的属性,添加为property装饰器以后,我们就可以向调用属性一样使用get方法
def name(self):
return self.__name
@name.setter # setter方法装饰器:@属性名.setter
def name(self,name):
self.__name = name
def setName(self,name):
if not isinstance(name,str) :
print('name must be string')
return
self.__name = name
@property
def age(self):
return self.__age
@age.setter
def age(self, age):
self.__age = age
def setAge(self,age):
if not isinstance(age,int) :
print('age must be int')
return
self.__age = age
@property
def sex(self):
return self.__sex
@sex.setter
def sex(self, sex):
self.__sex = sex
def setSex(self,sex):
if sex != 'man' and sex != 'woman' :
print('sex must be "man" or "woman"')
return
self.__sex = sex
def show(self):
print('Name:',self.__name)
print('Age:',self.__age)
print('Sex:',self.__sex)
p = Person('小明','18','man')
p.show()
本文地址:https://blog.csdn.net/tubulvxing1/article/details/110942863
上一篇: python---导入模块
下一篇: VC++字符串IP地址转DWORD地址