Communities for your favorite technologies. Explore all Collectives
Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work.
Bring the best of human thought and AI automation together at your work. Learn more
Find centralized, trusted content and collaborate around the technologies you use most.
Stack Internal
Knowledge at work
Bring the best of human thought and AI automation together at your work.
class Array: def __init__(self): self.list = [] def add(self, num): self.list.append(num) a = Array() a.add(1).add(2)
I would like to add number 1, 2 to self.list like this. How can I implement?
return self
add
After your insertion returns the instance itself for second operation, then you will have instance itself so you can perform add operation:
def add(self, num): self.list.append(num) return self
Add a comment
Return the object itself
As an alternative approach, why not just let your add method take a list of values as input? Seems like it would be easier to use like that
def add(self, vals): self.list += vals
So now you can
a.add([1,2])
Instead of
a.add(1).add(2)
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.
Start asking to get answers
Find the answer to your question by asking.
Explore related questions
See similar questions with these tags.
return selffromadd