实现抽象类之方式二

from abc import ABCMeta, abstractmethod


class Pay(metaclass=ABCMeta):   # 这种方式约束力强,但是依赖abc模块
    @abstractmethod
    def pay(self, money):
        """只要见到项目中有这种类,你的子类中必须实现和play同名的方法"""
        raise NotImplementedError('请在子类中重写与父类同名的方法')


class AliPay(Pay):
    def __init__(self, name):
        self.name = name

    def pay(self, money):
        dic = {'uname':self.name, 'price':money}
        print(f'{self.name}通过支付宝成功支付{money}元!')


class WeChatPay(Pay):
    def __init__(self, name):
        self.name = name

    def pay(self, money):
        dic = {'uname':self.name, 'price':money}
        print(f'{self.name}通过微信成功支付{money}元!')


class ApplePay(Pay):
    def __init__(self, name):
        self.name = name

    def pay(self, money):
        dic = {'uname': self.name, 'price': money}
        print(f'{self.name}通过苹果支付支付了{money}元!')


# aw = WeChatPay('alex')
# aw.pay(400)
#
# aa = AliPay('wusir')
# aa.pay(300)

# 归一化设计:
def pay(name, price, pay_kind):
    if pay_kind == 'WeChat':
        obj = WeChatPay(name)

    elif pay_kind == 'AliPay':
        obj = AliPay(name)

    elif pay_kind == 'ApplePay':
        obj = ApplePay(name)

    obj.pay(price)


pay('alex', 400, 'WeChat')
pay('wusir', 300, 'AliPay')
pay('eva-j', 500, 'ApplePay')

 

上一篇:tp5中ajax的搜索分页功能


下一篇:数据ETL-基于Python的数据预处理案例