zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    UITextField的简单操作和实际应用
    iOS
    单例传值
    改良UIScrollView滚动视图
    省市便利 UIPicherView
    滚动视图UIScrollView
    label自适应
    将图像设置成圆形
    笔记
    笔记
  • 原文地址:https://www.cnblogs.com/tyche116/p/13163305.html
Copyright © 2011-2022 走看看