Python property的应用-商品类

Python property的应用-商品类,第1张

# !/usr/bin/env python
# -*- coding:utf-8 -*-


"""
请按下列要求,完成一个商品类。
- 封装商品名,商品原价,以及折扣价。
- 实现一个获取商品实际价格的方法price。
- 接下来完成三个方法,利用属性组合完成下列需求:
  - 利用属性property将此price方法伪装成属性。
  - 利用setter装饰器装饰并实现修改商品原价。
  - 利用deltter装饰器装饰并真正删除原价属性。
"""

class Product:

    def __init__(self, name, price, discount):
        self.name = name
        self.__price = price
        self.__discount = discount

    @property
    def actual_price(self):
        return self.__price * self.__discount

    @actual_price.setter
    def actual_price(self, new_price):
        self.__price = new_price

    @actual_price.deleter
    def actual_price(self):
        del self.__price


iphone = Product('iphone', 5999, 0.9)
# print(iphone.actual_price())
print(iphone.actual_price)

# 伪装成 属性,对其进行价格修改
iphone.actual_price = 7000
print(iphone.actual_price)

# 删除商品的价格
del iphone.actual_price
print(iphone.__dict__)

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/990606.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存