Adding methods to Python classes

share on google plus share on facebook share on twitter share on linkedin share via email

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__)

3 Responses to “Adding methods to Python classes”

Leave a Reply to JJ

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>