从聚合中抑制属性

2024-04-26 18:12:21 发布

您现在位置:Python中文网/ 问答频道 /正文

BigTuple继承元组和聚合列表。__repr__无法按预期工作。也就是说,应该生成BigTuple(*(1,2,3)),但使用它聚合的列表的repr函数。如何抑制此行为并使用类BigTuple中定义的__repr__。我聚合列表是因为我想对初始化时提供的项目进行排序

我已尝试不汇总列表。例如:

self.__values = values 

而不是聚合:

self.__values = sorted(values)

请参阅下面的主代码

class BigTuple(tuple):

    def __init__(self, *values):

        self.__values = sorted(values)

    def __iadd__(self, other):
        assert hasattr(other, "__iter__")," Not an iterable"

        self.__values.extend(other)
        return self.__values

    def __repr__(self):  
        return 'BigTuple(*{!r})'.format(self.__values)



 cd = BigTuple((1,2,4,[5]))

 repr(cd)  # [1,2,4,[5]] instead of BigTuple(*(1,2,4,[5]))

Tags: 项目函数self列表return定义排序def