두 파이썬 클래스 인스턴스 간의 합계를 수행하고 모든 인스턴스 변수의 길이 목록을 가져 오는 방법

Pietro D' Antuono

여기 내 문제가 있습니다.

클래스의 두 인스턴스를 합산해야합니다 Foo. 클래스는 인스턴스 변수 barlist. 내 목표는 합 ( 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)

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Related 관련 기사

뜨겁다태그

보관