Python类方法装饰器

在创建类之后,可以通过直接修改类的属性来修改值,但一般不推荐这样修改,因此一般在类中会有特定的setter getter方法。

(但仍然可以修改属性,还是存在风险,可以把属性定义成私有属性)

class Car(object):
	__slots__ = ("color", "price")
	"""docstring for Car"""
	def __init__(self, color, price):
		super(Car, self).__init__()
		self.color = color
		self.price = price

	def set_price(self, newPrice):
		if isinstance(newPrice, int):
			if newPrice > 0 and newPrice < 100:
				self.price = newPrice
			else:
				price("too high")
		else:
			price("Type error")

	def get_price(self):
		return self.price

	def get_color(self):
		return self.color

if __name__ == "__main__":
	car1 = Car("Red", 120)
	print(car1.price)
	car1.set_price(30)
	car1.price = 23
	print(car1.get_price())

Python内置的@property装饰器可以把属性变成方法来用,实现的是getter功能

    @property
	def pprice(self):
		return self.price

这是@property又创建了一个方法@pprice:setter方法

	@pprice.setter
	def pprice(self,newPrice):
		if isinstance(newPrice, int):
			if newPrice > 0 and newPrice < 100:
				self.price = newPrice
			else:
				price("too high")
		else:
			price("Type error")

这样通过访问属性实现getter setter方法的自由切换,这样暴露出来的就是方法了

if __name__ == "__main__":
	car1 = Car("Red", 120)
	print(car1.pprice)
	car1.pprice = 23
	print(car1.pprice)

还可以定义只读属性,就是只有@property没有@func:setter方法

	@property
	def color(self):
		return self._color

注意方法和属性不能同名,这是调用就会报错:AttributeError: can't set attribute

property还有deleter方法

	@pprice.deleter
	def pprice(self):
		del self.price
	del car1.pprice
	try:
		print(car1.pprice)
	except Exception as e:
		print("error: ", e)

这是会报错:error:  'Car' object has no attribute 'price'

你可能感兴趣的:(python)