add method to loaded class/module in python

Question:

if I have something like

import mynewclass

Can I add some method to mynewclass? Something like the following in concept:

def newmethod(self,x):
    return x + self.y

mynewclass.newmethod = newmethod

(I am using CPython 2.6)

Asked By: hatmatrix

||

Answers:

Yes, if it’s a Python type. Except you’d do it on the class, not the module/package.

In Python the import statement is used for modules, not classes… so to import a class you need something like

from mymodule import MyClass

More to the point of your question the answer is yes. In Python classes are just regular objects and a class method is just a function stored in an object attribute.

Attributes of object instances in Python moreover are dynamic (you can add new object attributes at runtime) and this fact, combined with the previous one means that you can add a new method to a class at runtime.

class MyClass:
    def __init__(self, x):
        self.x = x

...

obj = MyClass(42)

def new_method(self):
    print("x attribute is", self.x)

MyClass.new_method = new_method

obj.new_method()

How can this work? When you type

obj.new_method()

Python will do the following:

  1. look for new_method inside the object obj.

  2. Not finding it as an instance attribute it will try looking inside the class object (that is available as obj.__class__) where it will find the function.

  3. Now there is a bit of trickery because Python will notice that what it found is a function and therefore will "wrap" it in a closure to create what is called a "bound method". This is needed because when you call obj.new_method() you want to call MyClass.new_method(obj)… in other words binding the function to obj to create the bound method is what takes care of adding the self parameter.

  4. This bound method is what is returned by obj.new_method, and then this will be finally called because of the ending () on that line of code.

If the search for the class also doesn’t succeed instead parent classes are also all searched in a specific order to find inherited methods and attributes and therefore things are just a little bit more complex.

Answered By: 6502
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.