Prasanna

pageicon Tuesday Apr 17, 2007

Python: Method overriding, How?

I have read Mark Pilgrim's Dive into Python several times, but this explanation on method overriding by Guido still puzzles me.

Guido, the original author of Python, explains method overriding this way: "Derived classes may override methods of their base classes. Because methods have no special privileges when calling other methods of the same object, a method of a base class that calls another method defined in the same base class, may in fact end up calling a method of a derived class that overrides it. (For C++ programmers: all methods in Python are effectively virtual.)" If that doesn't make sense to you (it confuses the hell out of me), feel free to ignore it. I just thought I'd pass it along.

Although I can interpret the statement, I still want to know HOW?
Comments:

You know how method dispatch in Python works right?
>>> class Foo:
	def bar(self):
		pass

>>> f = Foo()
>>> dir(f)
['__doc__', '__module__', 'bar']
>>> 
Evaluating `f.bar' means f's dictionary is looked up, otherwise f's base class.. and so.. on..

Posted by Sridhar Ratna on April 17, 2007 at 05:08 PM IST #

"a method of a base class that calls another method defined in the same base class, may in fact end up calling a method of a derived class that overrides it".

I agree every class has an associated dict, but I am not quite clear with the derived class which overrides it.

Posted by Prasanna Seshadri on April 17, 2007 at 06:18 PM IST #

Python searches attributes/methods in the MRO order. See, http://www.python.org/download/releases/2.3/mro/ Is that what you were looking for?

Posted by Sridhar Ratna on April 17, 2007 at 06:20 PM IST #

late binding

Posted by Nico on April 18, 2007 at 12:52 AM IST #

I too admire Python. Heard someone saying Ruby is better than Python, true? Oh well, what would be your suggestion for best beginner book to learn Python? Please consider my background too. I don't know why some people compare Python with C/C++/Java!? Python is scripting language and these are system programming languages. I don't like the comparison at all. Would Python be able to do what these languages do? Not at all!

Posted by Faisal on April 18, 2007 at 12:54 AM IST #

The best way to start is to download python and go through the excellent documentation available with the package. For beginners, A Byte of Python will help, once you finish it, start with Dive into Python .

Posted by Prasanna Seshadri on April 18, 2007 at 07:10 PM IST #

Post a Comment:
  • HTML Syntax: NOT allowed