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,520 points
4,006 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,890 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,880 points
12,970 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,880 points
5,414 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,890 points
1,217 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 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,398 views
0 votes
1 answer
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,890 points
2,360 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 24, 2020 in Python by Gitika
• 65,890 points
1,281 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP