标签:not price ice book error setter ISE instance must
对于私有属性常常会添加set以及get方法,此时可以使用Python内置的@property
装饰器,将set以及get方法简化为如同属性一样调用
示例:
普通情况:
class book: _score = 0 def __init__(self): self._score = 100 def get_price(self): return self._score def set_price(self,price): if not isinstance(price, int): raise ValueError(‘price must be an integer!‘) if price < 0 : raise ValueError(‘price must > 0 !‘) self._score = price b = book() b.set_price(100) print("book`s price is :",b.get_price())
执行输出;
使用了@property
装饰器之后
class book: _score = 0 def __init__(self): self._score = 100 @property def price(self): return self._score @price.setter def price(self,price): if not isinstance(price, int): raise ValueError(‘price must be an integer!‘) if price < 0 : raise ValueError(‘price must > 0 !‘) self._score = price b = book() b.price = 100 print("book`s price is :",b.price)
执行输出:
book`s price is : 100
标签:not price ice book error setter ISE instance must
原文地址:https://www.cnblogs.com/tyche116/p/13163305.html