学习Python并尝试学习制作课程。我定义了一个“Bag”类。对于__str__
我有:
def __str__(self):
return "<Bag: '{}' with {} items >".format(self.name, len(self.data))
它让我回来了:
<Bag: 'mystuff' with 3 items >
我__repr__
试图回复:<Bag: 'mystuff' with apple (1), pear (2) >
答案 0 :(得分:1)
from collections import Counter
def __repr__(self):
counter = Counter(self.data)
items = ', '.join('%s (%s)' % (name, count) for name, count in counter.iteritems())
return "<Bag: '{}' with {} >".format(self.name, items)