1
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?

3

3 Answers 3

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

Return the object itself

def add(self, num):
    self.list.append(num)
    return self

Comments

0

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)

Comments

Your Answer

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.

Ask question

Explore related questions

See similar questions with these tags.