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?

4
  • Why would you want to do something like that? Your shortened code looks way less readable to me. Commented May 22, 2022 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 Commented May 22, 2022 at 19:25
  • 3
    Does this answer your question? method chaining in python Commented May 22, 2022 at 19:26
  • I was just wondering if there was a shorter way if would ever need it... Commented May 22, 2022 at 19:46

3 Answers 3

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

Comments

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

Comments

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))

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.