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)
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.
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.
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, ...) .
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.
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.
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).
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With