统一的类属性检查

在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)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值