栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python property的应用-商品类

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python property的应用-商品类

# !/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__)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/755637.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号