python设计模式(一)--简单工厂(中)
2016-05-10 00:00
711 查看
摘要: 交互式收银计算器
最近正在持续更新源码库,代码都是参考大话设计模式翻成python版,完整代码片段请到github上去下载.
https://github.com/zhengtong0898/python-patterns
参考:
书籍<<大话设计模式>> 第二章 2.1 -- 2.3
Python 3.x
最近正在持续更新源码库,代码都是参考大话设计模式翻成python版,完整代码片段请到github上去下载.
https://github.com/zhengtong0898/python-patterns
参考:
书籍<<大话设计模式>> 第二章 2.1 -- 2.3
Python 3.x
[code=plain]# -.- coding:utf-8 -.- # __author__ = 'zhengtong' # 知识点:面向对象的编程,并不是类越多越好,类的划分是为了封装, # 但分类的基础是抽象,具有相同属性和功能的对象的抽象集合才是类。 _price_repr = '单价:' _number_repr = '数量:' _total_repr = '合计:' class CashSuper: """现金收取类(抽象类)""" def __init__(self, money): self.money = money def accept_cash(self): raise NotImplementedError class CashNormal(CashSuper): """正常收费子类""" def accept_cash(self): return self.money class CashRebate(CashSuper): """打折收费子类""" def __init__(self, rebate, **kwargs): """ 这里为什么采用**kwargs, 请参考下面这个链接: http://my.oschina.net/zhengtong0898/blog/670917 """ super(CashRebate, self).__init__(**kwargs) self.rebate = rebate def accept_cash(self): return self.money * self.rebate class CashReturn(CashSuper): """返利收费子类""" def __init__(self, condition, money_return, **kwargs): super(CashReturn, self).__init__(**kwargs) self.condition = int(condition) self.money_return = int(money_return) def accept_cash(self): result = self.money # 当满足了返利条件, 则采用计算规则. if self.money >= self.condition: result = self.money - int(self.money / self.condition) * self.money_return return result class CashFactory: """现金收费工厂类""" @staticmethod def create_cash_accept(typed, **kwargs): if typed == 1: result = CashNormal(**kwargs).accept_cash() elif typed == 2: result = CashReturn(300, 100, **kwargs).accept_cash() elif typed == 3: result = CashRebate(0.8, **kwargs).accept_cash() else: raise KeyError('无效的返利选择') return result def main(): result = 0 while True: try: prices = int(input(_price_repr)) number = int(input(_number_repr)) price_off = int(input('返利模式: 1(正常收费), 2(满300返100), 3(打8折):')) money = CashFactory.create_cash_accept(price_off, money=prices*number) result += money print(_price_repr, prices, _number_repr, number, _total_repr, money) except KeyboardInterrupt: print('') print('oops: 检测到Ctrl + C组合键, 正在返回总费用并推出程序') break return result if __name__ == '__main__': print('温馨提示:输入Ctrl + C组合键可得到总数和退出程序.') print(main())
相关文章推荐
- python占位符
- Python语言实现手机号归属地的方法
- python 编码
- 【NumPy】Windows下Python通过pip安装numPy的方法
- 解决IDAPython: importing "site" failed.的问题
- DayDayUP_Python自学教程[14]_python操作excel
- 使用python来实现报表自动化~
- python 调试工具
- 『Python』os库练习题及答案
- Python爬虫(二):整体设计
- zabbix实战调用短信接口报警
- Python:Python基础(二)
- ipython的安装
- 未解之谜:gb2312如何转到utf-8
- 统计字符串中的字符个数
- python for循环
- [Python]将Excel文件中数据导入MySQL
- Python requets 登录51cto家园
- python
- python之urllib2使用总结