Digging deep into python : Part 2 | Object level methods in python
Is it possible to redefine a class written in any programming language that you know? Yes. It is possible. So can you write a function particularly for an instance? Say I have an instance of class Calculator and there is only one function defined and that is for finding difference between two numbers. At one point when you created an instance, if you feel like to define one more function for a particular instance without affecting actual structure of the class or any other instances what should we do? To be more clear what should we do for creating instance level methods? In python there is a technique similar to monkey patching. We can bound any methods with one argument that is the instance itself to a particular instance in python. Below are the screen shots for doing the same.
Here in the screen shot you can see which all methods are bounded to the class Calculator and the first memory location of function where it referred.
You need to rewrite the above function sum() in the screen shot by adding one argument self if you wish to bind the sum() with obj1 instance. For binding, we use MethodType function from types package. Screen shot is given below.
In this screen shot you can see how we are binding a function to a particular instance without affecting the structure of class or an another object of the same class. So its one of the feature that I found in python which amused me. If any doubts feel free to ask by commenting..