How to invoke a function on an object dynamically by name

0 votes

In Python, say I have a string that contains the name of a class function that I know a particular object will have, how can I invoke it?

That is:

obj = MyClass() # this class has a method doStuff()
func = "doStuff"
# how to call obj.doStuff() using the func variable?
Dec 3, 2020 in Python by Roshni
• 10,420 points
102 views

1 answer to this question.

0 votes

Use "getattr": 

obj = MyClass()
try:
    func = getattr(obj, "dostuff")
    func()
except AttributeError:
    print "dostuff not found"
answered Dec 3, 2020 by Gitika
• 65,870 points

Related Questions In Python

0 votes
1 answer

How to call function that takes an argument in a Django template?

Hello @kartik, You cannot call a function that ...READ MORE

answered Jun 23, 2020 in Python by Niroj
• 82,580 points
2,839 views
0 votes
1 answer
0 votes
1 answer

How to get all links and all elements that are clickable on a page of system dynamically?

Hello, You can do it by using find_elements_by_xpath() driver ...READ MORE

answered Aug 27, 2020 in Python by Niroj
• 82,580 points
782 views
0 votes
1 answer

How to invoke a python static method inside class via string method name?

Use __import__ function to import the module by giving ...READ MORE

answered Dec 3, 2020 in Python by Gitika
• 65,870 points
58 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 1,858 views
0 votes
0 answers
0 votes
1 answer

I want to download a file from the website by web scraping. Can anyone explain how to do this in jupyter lab (python) with an example?

Hey, Web scraping is a technique to automatically ...READ MORE

answered Apr 7, 2020 in Python by Gitika
• 65,870 points
581 views
0 votes
1 answer

How to insert an object at a given index in Python?

Hi, @Roshni, I will explain to you with ...READ MORE

answered Jun 23, 2020 in Python by Gitika
• 65,870 points
96 views