1

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?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
gnicki
  • 53
  • 7
  • Why would you want to do something like that? Your shortened code looks way less readable to me. – Sören May 22 '22 at 19:24
  • 1
    What are you hoping to achieve? Do these "methods" explicitly return anything? Maybe you could describe your use-case in more detail – DarkKnight May 22 '22 at 19:25
  • 3
    Does this answer your question? [method chaining in python](https://stackoverflow.com/questions/12172934/method-chaining-in-python) – fsimonjetz May 22 '22 at 19:26
  • I was just wondering if there was a shorter way if would ever need it... – gnicki May 22 '22 at 19:46

3 Answers3

3

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)()
perperam
  • 432
  • 3
  • 10
2

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

DarkKnight
  • 19,739
  • 3
  • 6
  • 22
1

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))
cards
  • 3,936
  • 1
  • 7
  • 25