zoukankan      html  css  js  c++  java
  • 019: class, objects and instance: property

    属性在本质上来讲是一组方法,但是调用的时候却如同字段,换句话说,其实就是对字段的一种封装,在设定和读取的时候,可以很轻易的添加逻辑,而其调用方式其不会改变

    在Pyhon中可以用@property来定义:

    class Book(object):
        def __init__(self, title, price):
            self._title = title
            self._price = price
        
        @property
        def price(self):
            return "${}".format(self._price)        
    
        @price.setter    
        def price(self, value):
            self._price = value    
    
        @price.deleter
        def price(self):
            del self._price    
    
    book = Book("Python Basic", 100)
    
    print(book.price)        
    
    book.price = 200
    print(book.price)    
    
    del book.price
    print(book.price)    
        

    运行结果:

    $100
    $200
    Traceback (most recent call last):
      File "C:UsersMilespythonclass_object20160125_1.py", line 26, in <module>
        print(book.price)
      File "C:UsersMilespythonclass_object20160125_1.py", line 8, in price
        return "${}".format(self._price)
    AttributeError: 'Book' object has no attribute '_price'
  • 相关阅读:
    framework7 底部弹层popup js关闭方法
    div动画旋转效果
    面试题3
    面试题2
    CORS跨域请求[简单请求与复杂请求]
    面试题1
    nginx
    Pycharm配置支持vue语法
    Ajax在jQuery中的应用---加载异步数据
    jQuery开发入门
  • 原文地址:https://www.cnblogs.com/jcsz/p/5158790.html
Copyright © 2011-2022 走看看