临摹微笑
example (Buffer support << , Fee support + / +=)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647#!/usr/bin/env python# coding: utf-8 class Buffer(object): def __init__(self): self.buffer = [] def __lshift__(self, data): self.buffer.append(data) return self def __str__(self): return repr(self.buffer) class Fee(object): def __init__(self, qty=0, amount=0): self.qty = qty self.amount = amount def __radd__(self, another): return self if not another else self + another def __add__(self, another): return Fee( qty=self.qty + another.qty, amount=self.amount + another.amount ) def __repr__(self): return "%s(%s)" % ( self.__class__.__name__, ', '.join([ '%s=%r' % item for item in self.__dict__.items() ]) ) def tester(): buff = Buffer() buff <
博客给出了Python运算符重载的示例代码。定义了Buffer和Fee两个类,在Buffer类中重载了 << 运算符,Fee类中重载了 + 和 += 等运算符,展示了如何通过运算符重载实现特定功能。

2231

被折叠的 条评论
为什么被折叠?



