What is the difference between a static method and class method in Python?

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

Was this solution helpful to you?

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

Just Added Q & A:

Find solution

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.