What's the proper way to call a method that belongs to an object in Python when the name of the method is a variable?
-
class object: def newmethod(self): etc. etc. a = newmethod object.newmethod() works but object.__class__.__dict__[a]() returns newmethod() takes exactly one argument, 0 given
-
Answer:
I'd do: class myclass: def newmethod(self): ... obj = myclass() getattr(obj, 'newmethod')()
Adam Groszer at Quora Visit the source
Other answers
You need to pass in the object instance as the first parameter to the method. For example: class myclass: def newmethod(self): ... obj = myclass() obj.__class__.__dict__['newmethod'](obj) When you access the __class__ attribute of an instance, it returns an object that refers to the class in general and knows nothing about the particular instance that you requested it from. Hence, if you then retrieve an object describing an instance method (one that has 'self' as its first parameter), you need to tell it which object instance to operate on.
Anthony Yeh
Related Q & A:
- What's the safest way to clean a laptop screen?Best solution by Yahoo! Answers
- What's the quickest way to solve a Rubik's Cube?Best solution by Yahoo! Answers
- What is the proper way to open a laptop lid?Best solution by Yahoo! Answers
- What's the proper way of passing an argument to NSTimer?Best solution by Stack Overflow
- What's the best way to call from Europe to the US?
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
For every problem there is a solution! Proved by Solucija.
-
Got an issue and looking for advice?
-
Ask Solucija to search every corner of the Web for help.
-
Get workable solutions and helpful tips in a moment.
Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.