简体   繁体   English

对象列表的自定义列表表示

[英]Custom list representation for list of objects

I know that representation of an object can customized be using the __repr__ magic method. 我知道可以使用__repr__魔术方法来自定义对象的表示形式。

class A:

    ...

    def __repr__(self):
        return 'A(id={})'.format(self.id)

Is there a way to customize the representation when it is a list of these objects, such that it doesn't just print a list of the object's representation [A(id=1), A(id=10), A(id=11)] . 当存在这些对象的列表时,有没有一种方法可以自定义表示,因此它不只是打印对象表示的列表[A(id=1), A(id=10), A(id=11)]

For example: 例如:

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)]

I was thinking of wrapping the list into another object before assigning to self.lst so that I can modify its repr. 我在考虑将该列表包装到另一个对象中,然后self.lstself.lst以便我可以修改其repr。 Any other idea? 还有其他想法吗?

You can store the list passed to the AGroup constructor in an instance of a sub-class of list , so that you can override the __repr__ method of the list sub-class to return an output in your desired format: 您可以存储传递给列表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)

This outputs: 输出:

<Group of 3 A's>

to group class instance we need to overwrite eq, ne, and hash function. 要对类实例进行分组,我们需要覆盖eq,ne和hash函数。 by giving the static hash value will treat all instances of this class as one object. 通过提供静态哈希值,会将此类的所有实例视为一个对象。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM