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

问题描述

这是我的问题。

我必须对 Foo 类的两个实例求和。该类接受实例变量 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,4]?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)