Overriding methods on a per instance basis

Steve D'Aprano steve+python at pearwood.info
Tue May 30 21:31:01 EDT 2017


On Tue, 30 May 2017 12:00 pm, Kunal Jamdade wrote:

> I tried to understand  overriding methods on per instance class. But i am
> not getting it. Can you help me in getting the mail. Or can u suggest me at
> least what should i read before reading "this topic"?
> 
> Can you explain me with one more example?

Do you understand how methods work normally?

If you don't understand Object Oriented programming and methods, you will have
difficulty with this concept. You could try these:

https://en.wikibooks.org/wiki/Non-Programmer's_Tutorial_for_Python_3/Intro_to_Object_Oriented_Programming_in_Python_3

http://www.python-course.eu/object_oriented_programming.php


but I don't know how good they are.


Normally methods are defined by the class, and are shared by all instances. So
if I have:


py> class Person(object):
...     def speak(self):
...         return "Hello!"
...
py> fred = Person()
py> sally = Person()
py>
py> fred.speak()
'Hello!'
py> sally.speak()
'Hello!'


then both instances, fred and sally, have the same "speak" method.

But what if you want to give *just one* instance a special method that the other
instances don't have? In Python, that is easy: just give the instance a
callable attribute. For simple cases, we can use lambda to create a function:

py> fred.shout = lambda: "I'm shouting!"
py> fred.shout()
"I'm shouting!"


For more complicated cases, you may need to use types.MethodType.

Now the fred instance alone has access to this "method" shout. If you try it
from another instance, you get an error:

py> sally.shout()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Person' object has no attribute 'shout'


That's not all: we can also override fred's "speak" method:

py> fred.speak = lambda: "I like to yell and shout."
py> fred.speak()
'I like to yell and shout.'
py> sally.speak()
'Hello!'


Now fred.speak is customised, while all other instances use the original.




-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list