Monkey Patching

suggest change

In this case, “monkey patching” means adding a new variable or method to a class after it’s been defined. For instance, say we defined class A as

class A(object):
    def __init__(self, num):
        self.num = num

    def __add__(self, other):
        return A(self.num + other.num)

But now we want to add another function later in the code. Suppose this function is as follows.

def get_num(self):
    return self.num

But how do we add this as a method in A? That’s simple we just essentially place that function into A with an assignment statement.

A.get_num = get_num

Why does this work? Because functions are objects just like any other object, and methods are functions that belong to the class.

The function get_num shall be available to all existing (already created) as well to the new instances of A

These additions are available on all instances of that class (or its subclasses) automatically. For example:

foo = A(42)

A.get_num = get_num

bar = A(6);

foo.get_num() # 42

bar.get_num() # 6

Note that, unlike some other languages, this technique does not work for certain built-in types, and it is not considered good style.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents