Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get class that defined method

How can I get the class that defined a method in Python?

I'd want the following example to print "__main__.FooClass":

class FooClass:     def foo_method(self):         print "foo"  class BarClass(FooClass):     pass  bar = BarClass() print get_class_that_defined_method(bar.foo_method) 
like image 213
Jesse Aldridge Avatar asked Jun 07 '09 02:06

Jesse Aldridge


People also ask

How do I know what class a method is in Python?

To list the methods for this class, one approach is to use the dir() function in Python. The dir() function will return all functions and properties of the class.

What is def __ str __?

The __str__ method in Python represents the class objects as a string – it can be used for classes. The __str__ method should be defined in a way that is easy to read and outputs all the members of the class. This method is also used as a debugging tool when the members of a class need to be checked.

What is the __ call __ method?

The __call__ method enables Python programmers to write classes where the instances behave like functions and can be called like a function. When the instance is called as a function; if this method is defined, x(arg1, arg2, ...) is a shorthand for x. __call__(arg1, arg2, ...) .

What is the use of getClass() method in Java?

getClass () is the method of Object class. This method returns the runtime class of this object. The class object which is returned is the object that is locked by static synchronized method of the represented class. It returns the Class objects that represent the runtime class of this object.

How do you call a class method in Python?

So we can call the class method both by calling class and object. A classmethod () function is the older way to create the class method in Python. In a newer version of Python, we should use the @classmethod decorator to create a class method. Using the class method, we can only access or modify the class variables.

Why do we know which class defined a method?

IMHO there are two reasons one would want to know which class defined a method; first is to point fingers at a class in debug code (such as in exception handling), and the second is to determine if the method has been re-implemented (where method is a stub meant to be implemented by the programmer).

What is the classmethod () function in Python?

The classmethod () is an inbuilt function in Python, which returns a class method for a given function. function: It is the name of the method you want to convert as a class method.


1 Answers

import inspect  def get_class_that_defined_method(meth):     for cls in inspect.getmro(meth.im_class):         if meth.__name__ in cls.__dict__:              return cls     return None 
like image 98
Alex Martelli Avatar answered Sep 26 '22 18:09

Alex Martelli