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.. 


  1. I simply wanted to write down a quick word to say thanks to you for those wonderful tips and hints you are showing on this site.
    It’s great to come across a blog every once in a while that isn’t the same out of date rehashed material. Fantastic read.

    Python Training in Chennai | Python Training Institutes in Chennai

  2. I believe there are many more pleasurable opportunities ahead for individuals that looked at your site.
    Python Training in Bangalore

  3. Really very informative and creative contents. This concept is a good way to enhance the knowledge.thanks for sharing. please keep it up

    python training in chennai

    hadoop training in chennai

  4. This comment has been removed by the author.

  5. I am a regular reader of your blog and being students it is great to read that your responsibilities have not prevented you from continuing your study and other activities. Love
    Python Online training
    Python Course institute in Bangalore

  6. Attend The Python Training in Bangalore From ExcelR. Practical Python Training in Bangalore Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Python Training in Bangalore.


Post a Comment

Popular Posts