Monkey Patching
suggest changeIn 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 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) instances of A, as well as to new ones.
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.