[英]Custom list representation for list of objects
我知道可以使用__repr__
魔术方法来自定义对象的表示形式。
class A:
...
def __repr__(self):
return 'A(id={})'.format(self.id)
当存在这些对象的列表时,有没有一种方法可以自定义表示,因此它不只是打印对象表示的列表[A(id=1), A(id=10), A(id=11)]
。
例如:
class AGroup:
def __init__(self, lst):
self.lst = lst
>>> lst = [A(1), A(10), A(11)]
>>> grp = AGroup(lst)
>>> grp.lst
<Group of 3 A's> # instead of [A(id=1), A(id=10), A(id=11)]
我在考虑将该列表包装到另一个对象中,然后self.lst
给self.lst
以便我可以修改其repr。 还有其他想法吗?
您可以存储传递给列表AGroup
构造一个子类的实例list
,这样就可以覆盖__repr__
的方法list
子类在你想要的格式返回的输出:
class A:
def __init__(self, id):
self.id = id
def __repr__(self):
return 'A(id={})'.format(self.id)
class AGroup:
class AList(list):
def __repr__(self):
return "<Group of %d A's>" % len(self)
def __init__(self, lst):
self.lst = self.AList(lst)
lst = [A(1), A(10), A(11)]
grp = AGroup(lst)
print(grp.lst)
输出:
<Group of 3 A's>
要对类实例进行分组,我们需要覆盖eq,ne和hash函数。 通过提供静态哈希值,会将此类的所有实例视为一个对象。
from collections import Counter
class A:
def __init__(self , id):
self.id = id
def __hash__(self): return hash('A')
def __eq__(self, x): return type(x) is A
def __ne__(self, x): return type(x) is not A
def __repr__(self):
return 'A'
class B:
def __init__(self , id):
self.id = id
def __hash__(self): return hash('B')
def __eq__(self, x): return type(x) is B
def __ne__(self, x): return type(x) is not B
def __repr__(self):
return 'B'
class AGroup:
def __init__(self, lst):
count = Counter(lst)
self.lst = []
for cl in Counter(lst):
self.lst.append('<Group of {} {}\'s>'.format(count[cl] , cl))
lst = [A(1), B(10), A(11)]
grp = AGroup(lst)
grp.lst
["<Group of 2 A's>", "<Group of 1 B's>"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.