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

  • 相关阅读:
    架构师之路
    责任链设计模式
    Junit框架分析
    线程详解
    课程总结
    IO流
    Java第四次作业
    Character string
    实训
    实训SI
  • 原文地址:https://www.cnblogs.com/tyche116/p/13163305.html
Copyright © 2011-2022 走看看