I need to do something like this:
abc = xyz()
abc.method1()
abc.method2()
abc.method3()
...
Is there a way to shorten this? Like:
abc= xyz()
abc.{method1(),method2(),method3(),...}
or something?
I need to do something like this:
abc = xyz()
abc.method1()
abc.method2()
abc.method3()
...
Is there a way to shorten this? Like:
abc= xyz()
abc.{method1(),method2(),method3(),...}
or something?
You can call a objects method by string using the getattr()
function build into python.
class xyz():
def method0(self):
print("1")
def method1(self):
print("2")
abc = xyz()
# use this if you have numbers
for i in range(2):
getattr(abc, f"method{i}")()
# use this if you have a list of methods
names = ["method0", "method1"]
for name in names:
getattr(abc, name)()
You can do this by ensuring that the instance functions (methods) each return a reference to the instance in which they are running (self)
class xyz:
def method1(self):
print('m1')
return self
def method2(self):
print('m2')
return self
def method3(self):
print('m3')
return self
abc = xyz()
abc.method1().method2().method3()
Output:
m1
m2
m3
Observation:
Whilst it can be done, I offer this merely as an answer to the original question. I do not condone the practice
For a systematic approach and keeping the integrity of the methods use methodcaller
. Compatible with arguments, see doc.
from operator import methodcaller
obj = xyz()
m_names = ['method1', 'method2', 'method3']
for name in m_names:
print(methodcaller(name)(obj))