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

Comments

  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

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

    ReplyDelete
  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

    ReplyDelete

Post a Comment

Popular Posts