Adding methods to Python classes
The normal way to add functionality (methods) to a class in Python is to define functions in the class body. There are many other ways to accomplish this that can be useful in different situations.
This is the traditional way
class A(object): def print_classname(self): print self.__class__.__name__
The method can also be defined outside the scope of the class. This allows the function “print_classname” to be used as a standalone function and as a method of the class.
def print_classname(a): print a.__class__.__name__ class A(object): print_classname = print_classname
Or, equivalently
def print_classname(a): print a.__class__.__name__ class A(object): pass setattr(A, "print_classname", print_classname)
Adding the method to an object of type “A” is also possible. However, you need to specify that the attribute “print_classname” of the object is a method to make sure it will receive a reference to “self” as implicit first parameter when it is called.
from types import MethodType def print_classname(a): print a.__class__.__name__ class A(object): pass # this assigns the method to the instance a, but not to the class definition a = A() a.print_classname = MethodType(print_classname, a, A) # this assigns the method to the class definition A.print_classname = MethodType(print_classname, None, A)
Specific methods from another class can also be added (without inherit everything else) by adding the underlying function of the method. Otherwise the method will expect a reference to an instance of the original class as implicit first parameter.
class B(object): def print_classname(self): print self.__class__.__name__ # option 1 class A(object): print_classname = B.print_classname.__func__ # option 2 class A(object): pass setattr(A, "print_classname", B.print_classname.__func__)
Great writeup. Is there a way to add a method to a different class in Python 3? __func__ is gone
not sure, but i think you can’t as the concept of an *unbound* method has disappeared in Python 3 (see: https://stackoverflow.com/questions/3589311/get-defining-class-of-unbound-method-object-in-python-3/25959545#25959545)…
nice to hear this. you have the great site!