Adding methods dynamically in Python
Given the dynamic nature of Python you can do many things in runtime, like add methods dynamically to an object or class. This is particularly useful when writing unit tests.
Here is the simplest way, adding a method to and object:
note that play
is just a function, it doesn’t receive self. There is no way to p
knows that it’s a method. If you need self
, you must create a method and then bind to the object:
In these examples, only the p
instance will have play
method, other instances of Person
won’t. To accomplish this we need to add the method to the class:
note that we don’t need to create a method with types.MethodType
here, because all functions in the body of a class will become methods and receive self
, unless you explicit say it’s a classmethod
or staticmethod
.
Adding methods to builtin types
Python doesn’t allow to add methods to built-in types, actually to any type defined in C. The unique way around this is to subclass the type, here is an example:
Here is a nice comparison on dynamically adding methods in Python and Ruby.