class Item:
def __init__(self, name, **kwargs):
self.name = name
self._spec = kwargs
def __repr__(self):
return "{}={}".format(self.name, self._spec)
class Cart:
def __init__(self):
self.items = []
def __len__(self):
return len(self.items)
def additem(self, item):
self.items.append(item)
def __add__(self, other):
print(other)
if isinstance(other, Item):
self.items.append(other)
return self
def __getitem__(self, index):
return self.items[index]
def __iter__(self):
return iter(self.items) # cart对象变为迭代器
def __repr__(self):
return str(self.items)
cart = Cart()
print(cart+2+3+4+5) # 运算符重载