这是我的问题。
我必须总结该类的两个实例Foo
。该类将实例变量接受bar
为list
。我的目标是在加法期间计算除总和(在list
某种意义上)以外的另一个列表,该列表包含every的长度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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句