0

how can i call multiple methods of an object at the same time in python. in php I can do this:

class Client{
    public ac1(){ ... }

    public ac2(){ ... }
}

$client = new client();
$client->ac1()->ac2(); <-- I want to do it here

how would you do it in python?

0

1 Answer 1

3

The example you gave of PHP code does not run the methods at the same time - it just combines the 2 calls in a single line of code. This pattern is called a fluent interface.

You can do the same in Python as long as a method you're calling returns the instance of the object it was called on.

I.e.:

class Client:
    def ac1(self):
        ...
        return self

    def ac2(self):
        ...
        return self


c = Client()
c.ac1().ac2()

Note that ac1() gets executed first, returns the (possibly modified in-place) instance of the object and then ac2() gets executed on that returned instance.

Some major libraries that are popular in Python are moving towards this type of interface, a good example is pandas. It has many methods that allow in-place operations, but the package is moving towards deprecating those in favour of chainable operations, returning a modified copy of the original.

Sign up to request clarification or add additional context in comments.

2 Comments

Wasn't returning the self. thank you so much. It worked out!
You're welcome. If the response answers your question, consider clicking the checkmark next to it so that your question no longer appears as unanswered. If you require further help, add a comment detailing it, or update your question.

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.