簡體   English   中英

如何在兩個 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM