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:


Classes:
* Monkey Patching
*

Table Of Contents
2 Filter
3 List
7 Loops
22 Reduce
27 Classes
31 Set
42 Tuple
45 Enum
62 Sockets
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve