• 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'
  • 相关阅读:
    HDU4608+模拟
    七、cocos2dx之粒子系统
    组织机构代码校验码 验证程序
    公民身份号码 校验码 检证程序
    百度地图之短串分享
    HDU 1421 DP
    动物:黄鼬、黄鼠狼
    动物-昆虫-蜂:马蜂
    动物-昆虫-蜂:青米蜂
    动物-昆虫-蜂:土蜂
  • 原文地址:https://www.cnblogs.com/jcsz/p/5158790.html
Copyright © 2020-2023  润新知