Python中property描述器的使用
property描述器可以让访问方法时使用属性访问的语法:
>>> class Person: ... def __init__(self, name): ... self.__name = name ... def get_name(self): ... return '姓名:' + self.__name ... def set_name(self, name): ... if not isinstance(name, str): ... raise TypeError('名字必须是字符串!') ... self.__name = name ... name = property(get_name, set_name)
... >>> >>> p = Person('韩晓萌') >>> p.name '姓名:韩晓萌' >>> p.name = 1 Traceback (most recent call last): File "<pyshell#13>", line 1, in <module> p.name = 1 File "<pyshell#10>", line 8, in set_name raise TypeError('名字必须是字符串!') TypeError: 名字必须是字符串! >>> p.name = '杨超越' >>> p.name '姓名:杨超越'
采用装饰器语法:
>>> class Person: ... def __init__(self, name): ... self.__name = name ... @property ... def name(self): ... return '姓名:' + self.name ... @name.setter ... def set_name(self, name): ... if not isinstance(name, str): ... raise TypeError('名字必须是字符串!') ... self.name = name
... >>> >>> p = Person('韩晓萌') >>> p.name '姓名:韩晓萌' >>> p.name = 1 Traceback (most recent call last): File "<pyshell#31>", line 1, in <module> p.name = 1 File "<pyshell#28>", line 12, in name raise TypeError('名字必须是字符串!') TypeError: 名字必须是字符串! >>> p.name = '杨超越' >>> p.name '姓名:杨超越'