在python中写class时很常用的方法是 @property 和 setter, 如下代码:
class Person():
def __init__(self, firstname, lastname):
# 这里用self.firstname 而不是 self._firstname,
# 用前者能在__init__里能调用 @firstname.setter
self.firstname = firstname
self.lastname = lastname
@property
def firstname(self):
return self._firstname
@firstname.setter
def firstname(self, firstname):
if not isinstance(firstname, str):
raise TypeError('need a str')
self._firstname = firstname
#重复的代码
@property
def lastname(self):
return self._lastname
@lastname.setter
def lastname(self, lastname):
if not isinstance(lastname, str):
raise TypeError('need a str')
self._lastname = lastname
这里有个问题,对属性的检查有重复的代码
改善 代码如下
class Name:
def __init__(self, name):
self.name = name
def __get__(self, instance, cls):
if instance is None:
return self
else:
return instance.__dict__[self.name]
def __set__(self, instance, value):
if not isinstance(value, str):
raise TypeError('need a str')
instance.__dict__[self.name] = value
class Person():
firstname = Name('firstname')
lastname = Name('lastname')
def __init__(self, firstname, lastname):
self.firstname = firstname
self.lastname = lastname
if __name__ == '__main__':
p = Person('aaa', 'bbb')
p.firstname = 'ccc'
p.lastname = 'ddd123'
print (p.firstname, p.lastname)