如何在两个 python class 实例之间执行求和并获取每个实例变量的长度列表

How to perform sum between two python class instances and get the list of length of every instance variable

这是我的问题。

我必须对 class Foo 的两个实例求和。 class 接受实例变量 bar 作为 list。我的目标是在加法期间计算,除了总和(在 list 意义上),另一个列表包含每个 instance.bar 的长度。 当然,我到目前为止所取得的成就不适用于涉及两个以上附录的总和,因为它总是会提供一个长度为 2 的列表。

非常感谢您的帮助。

到目前为止,这是我的代码。

class Foo():

    def __init__(self, bar: list):
        if isinstance(bar, list):
            self.bar = bar
        else:
            raise TypeError(f"{bar} is not a list")  

    def __add__(self, other):
        if isinstance(other, Foo):
            added_bar = self.bar + other.bar
            added_foo = Foo(added_bar)
        else:
            raise TypeError(f"{other} is not an instance of 'Foo'")
        added_foo.len_bars = [len(self.bar)] + [len(other.bar)]
        return added_foo

    def __radd__(self, other):
        if other == 0:
            return self
        else:
            return self.__add__(other)

a = Foo([1, 2, 3])
b = Foo([4, 5])
c = Foo([7, 8, 9, "a"])

r = a+b+c
print(r.len_bars) # prints [5, 4], is there a way to have [3, 2, 4]?

听起来您想在添加中包含之前未包含的长度,或者在添加中包含之前的长度列表(如果之前已包含)。我更新了代码。

class Foo():

    def __init__(self, bar: list):
        if isinstance(bar, list):
            self.bar = bar
        else:
            raise TypeError(f"{bar} is not a list")  

    def __add__(self, other):
        if isinstance(other, Foo):
            added_bar = self.bar + other.bar
            added_foo = Foo(added_bar)
        else:
            raise TypeError(f"{other} is not an instance of 'Foo'")
        self_len_bars      = self.len_bars  if hasattr(self,'len_bars')  else [len(self.bar)]
        other_len_bars     = other.len_bars if hasattr(other,'len_bars') else [len(other.bar)]
        added_foo.len_bars = self_len_bars + other_len_bars
        return added_foo

    def __radd__(self, other):
        if other == 0:
            return self
        else:
            return self.__add__(other)

a = Foo([1, 2, 3])
b = Foo([4, 5])
c = Foo([7, 8, 9, "a"])

r = a+b+c
print(r.len_bars)