Python特性

class Quantity:

    def __init__(self, storage_name):
        """
        :param storage_name: 托管类中实例属性
        """
        self.storage_name = storage_name
        # print('我被初始化qq')

    def __set__(self, instance, value):
        """
        :param instance: 托管类实例
        :param value: 托管类实例属性赋值
        :return:
        """
        print(self, 1111)
        if value > 0:
            instance.__dict__[self.storage_name] = value
        else:
            raise ValueError('value must > 0')


class LineItem:
    weight = Quantity('weight')
    price = Quantity('price')

    def __init__(self, descriptor, weight, price):
        """
        :param descriptor: 物品描述
        :param weight: 物品重量
        :param price: 价格
        """
        self.descriptor = descriptor
        self.weight = weight
        self.price = price
        print('我被初始化ll')

    def subtotal(self):
        """
        :return: 总价值
        """
        return self.weight * self.price

python拥有特性,但是这个特性貌似只对类开放,对函数并没有完全开放。

函数如果也想变成特性,就需要property装饰器,通过闭包的形式把闭包内函数设置为类属性

类属性 = property(func)

 

def quantity(storage_name):

    def qty_getter(instance):
        print(instance)
        return instance.__dict__[storage_name]

    def qty_setter(instance, value):
        if value > 0:
            instance.__dict__[storage_name] = value
        else:
            raise ValueError('value must > 0')

    return property(qty_getter, qty_setter)

"""
def func1():
    def func(selfs):
        print(selfs.subtotal())
        return '感谢'
    return func
"""

class LineItem:

    weight = quantity('weight')
    price = quantity('price')
    # auto_mi = func1()

    def __init__(self, description, weight, price):
        self.description = description
        self.weight = weight
        self.price = price

    def subtotal(self):
        return self.weight * self.price

 

转载于:https://www.cnblogs.com/PHUN19/p/11312489.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值