can i implement virtual functions in python ?

Stephen Horne $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk
Wed Oct 1 12:03:59 EDT 2003


On 30 Sep 2003 07:53:07 -0700, prabua at hotmail.com (Prabu) wrote:

>Hi,
>
>I'm new to python, so excuse me if i'm asking something dumb. 
>Does python provide a mechanism to implement virtual functions?
>Can you please give a code snippet also...:)
>Thanx in advance
>-Prabu.

As others have said, in Python all methods are effectively virtual.

Late (or dynamic) binding is the object-oriented ideal, and that is
what virtual methods give you in C++.

In C++, dynamic binding requires a 'virtual table' to provide the link
from an instance object to the appropriate implementation of a virtual
method. The instance object contains a pointer to the virtual table,
which in turn contains effectively a function pointer for each virtual
method.

This is done purely so that the caller need not know exactly what
class it is calling and yet the correct implementation of the method
will be invoked. The decision of exactly what implementation of that
function to call is made at runtime (ie late) rather than at compile
time.

The trouble is that this virtual-table lookup is sometimes considered
slow. A statically bound (or early bound) method is a little faster
because the decision of what implementation to call has been made by
the compiler at each point where the method is called. Virtual table
lookup isn't needed.

Basically, a C++ virtual method call is implemented something like the
following...

  (instance_obj->vtable [method_id]) (instance_obj, other_args);

Whereas a C++ non-virtual method call is simply...

  method_fn (instance_obj, other_args);

(this is, I think, only the single inheritance case - things may be a
bit more complex for multiple inheritance)

Python is a much more dynamic language than terms such as 'early
binding' would imply. Each call has a lookup by name at the time it is
called. This certainly supports dynamic binding, but goes further -
you can pass any instance object that provides the required set of
methods to a function and that function will just work.

If your reason for using a base class to your subclasses is simply so
that the same functions/classes can call shared methods in the
subclasses, this is unnecessary and provides few benefits in Python.
Python classes tend to share a 'protocol' rather than an explicit
interface. At least 90% of the time, inheritance in Python is just a
shorthand for creating a class which implements the same protocol (and
a way of making the relationship more explicit in the source code, of
course). Actually checking the type of an instance object is quite
rare in my experience.


-- 
Steve Horne

steve at ninereeds dot fsnet dot co dot uk




More information about the Python-list mailing list