如何创建委托类而不是子类?

时间:2019-03-15 20:21:19

标签: python python-3.x

为了编写一些非Python的代码,我尝试实现了技巧https://docs.python.org/3/faq/programming.html#id55,在这里我将使用带有委托的类(DelegatedLoanContract)而不是子类(LoanContract(ContractsWriter) )。但是我得到了:TypeError: unsupported operand type(s) for +=: 'DelegatedLoanContract' and 'str'。知道如何解决吗?

代码如下:https://github.com/Laurentiu-Andronache/fun-with-delegation

这也是该代码的最低版本:

class ContractsWriter:
    def __init__(self, signee_1, signee_2):
        self.signee_1 = signee_1
        self.signee_2 = signee_2
        self.contract_rules = []

    def __add__(self, other):
        if isinstance(other, str):
            self.contract_rules.append(other)
            return self
        elif isinstance(other, list):
            self.contract_rules.extend(other)
            return self
        else:
            raise NotImplemented('Invalid rule.')

class DelegatedLoanContract:
    def __init__(self, *args, **kwargs):
        self.__dict__['_contract'] = ContractsWriter(*args, **kwargs)
        self._contract.header = 'loan'

    def __getattr__(self, item):
        return getattr(self._contract, item)

    def __setattr__(self, key, value):
        setattr(self._contract, key, value)

if __name__ == '__main__':
    loan_contract = DelegatedLoanContract('Alan', 'John')
    loan_contract += 'Signee_1 will load 2,000 EUR to Signee_2.'

1 个答案:

答案 0 :(得分:1)

如果您要谈论委托,则必须编写__iadd__的{​​{1}}方法,该方法将委托给DelegatedLoanContract的{​​{1}}方法:

__add__