Python – call multiple methods in a single call
Question:
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?
Answers:
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.
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?
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.