Python @property装饰器

对于私有属性常常会添加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())

执行输出;

book`s price is : 100

使用了@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

posted @ 2020-06-19 15:28  漆天初晓  阅读(238)  评论(0编辑  收藏  举报