Python #@property属性

#-*- coding:utf-8 -*-
# class Foo:
#     def func(self):
#         print 'func'
#
#     # 定义属性
#     @property
#     def prop(self):
#         print 'prop'
#
# foo_obj = Foo()
# foo_obj.func()
# foo_obj.prop

# 属性存在意义是:访问属性时可以制造出和访问字段完全相同的假象

# 属性由方法变种而来,如果Python中没有属性,方法完全可以代替其功能

#实例
# ############### 定义 ###############
class Pager:
    def __init__(self, current_page):
        # 用户当前请求的页码(第一页、第二页...)
        self.current_page = current_page
        # 每页默认显示10条数据
        self.per_items = 10

    @property
    def start(self):
        if self.current_page == 1:
            val = 1
        else:
            val = self.current_page * 10 - 9
        return val

    @property
    def end(self):
        val = self.current_page * self.per_items
        return val

# ############### 调用 ###############
p = Pager(1)
print p.start
# 就是起始值,即:m
print p.end
# 就是结束值,即:n

新式类,具有三种@property装饰器

#-*- coding:utf-8 -*-
class Goods(object):
    def __init__(self):
        # 原价
        self.original_price = 100
        # 折扣
        self.discount = 0.8

    @property
    def price(self):
        # 实际价格 = 原价 * 折扣
        new_price = self.original_price * self.discount
        return new_price

    @price.setter
    def price(self, value):
        self.original_price = value

    @price.deleter
    def price(self):
        # del self.original_price
        print 'price.deleter'
    
obj = Goods()
print obj.price       # 获取商品价格
obj.price = 200       # 修改商品原价
print obj.price
del obj.price         # 删除商品原价

经典类

class Goods:
    @property
    def price(self):
        return "xxxxxxxxxxxx"
# 调用 
obj = Goods()
result = obj.price  # 自动执行 @property 修饰的 price 方法,并获取方法的返回值
原文地址:https://www.cnblogs.com/lwsup/p/7582016.html