Skip to main content
deleted 19 characters in body
Source Link
Guimo
  • 186
  • 3

Another solution for completionMy two cents.

class A():
    def __init__(self, arg):
        self.arg = arg

class AB():
    def __init__(self):
        pass

    def __iadd__(self, other):
        if not hasattr(self, '_list'):
            setattr(self, '_list', [other])
        else:
            self._list.append(other)
        
        return self

ab = AB()
ab += A(1)
ab += A(3)

print(ab._list[1].arg) # Prints 3

We completely avoid the creation of the _list parameter, unless we add an A() object.

Note that we are overriding the += operator specifically.

Another solution for completion.

class A():
    def __init__(self, arg):
        self.arg = arg

class AB():
    def __init__(self):
        pass

    def __iadd__(self, other):
        if not hasattr(self, '_list'):
            setattr(self, '_list', [other])
        else:
            self._list.append(other)
        
        return self

ab = AB()
ab += A(1)
ab += A(3)

print(ab._list[1].arg) # Prints 3

We completely avoid the creation of the _list parameter, unless we add an A() object.

Note that we are overriding the += operator specifically.

My two cents.

class A():
    def __init__(self, arg):
        self.arg = arg

class AB():
    def __init__(self):
        pass

    def __iadd__(self, other):
        if not hasattr(self, '_list'):
            setattr(self, '_list', [other])
        else:
            self._list.append(other)
        
        return self

ab = AB()
ab += A(1)
ab += A(3)

print(ab._list[1].arg) # Prints 3

We completely avoid the creation of the _list parameter, unless we add an A() object.

Note that we are overriding the += operator specifically.

Source Link
Guimo
  • 186
  • 3

Another solution for completion.

class A():
    def __init__(self, arg):
        self.arg = arg

class AB():
    def __init__(self):
        pass

    def __iadd__(self, other):
        if not hasattr(self, '_list'):
            setattr(self, '_list', [other])
        else:
            self._list.append(other)
        
        return self

ab = AB()
ab += A(1)
ab += A(3)

print(ab._list[1].arg) # Prints 3

We completely avoid the creation of the _list parameter, unless we add an A() object.

Note that we are overriding the += operator specifically.