(no subject)

Michael Chermside mcherm at mcherm.com
Tue Sep 30 11:33:35 EDT 2003


Prabu writes:
> I'm new to python, so excuse me if i'm asking something dumb. 

Hey, everyone had to start someplace, we try hard to be nice
to newbies here. You can also check out the beginners list
(http://mail.python.org/mailman/listinfo/tutor), where they
SPECIALIZE in being clear to newbies.

> Does python provide a mechanism to implement virtual functions?

Yes. If by "virtual function" you mean what is meant in C++, then
*all* functions in Python are virtual.

> Can you please give a code snippet also...:)

Of course!

  G:\>python
  Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on win32
  Type "help", "copyright", "credits" or "license" for more information.
  >>> class Animal(object):
  ...    def speak(self):
  ...        pass
  ...
  >>> class Dog(Animal):
  ...     def speak(self):
  ...         print 'Woof'
  ...
  >>> class Cat(Animal):
  ...     def speak(self):
  ...         print 'Miow'
  ...
  >>> class Giraffe(Animal):
  ...     pass
  ...
  >>> dog = Dog()
  >>> cat = Cat()
  >>> giraffe = Giraffe()
  >>> dog.speak()
  Woof
  >>> cat.speak()
  Miow
  >>> giraffe.speak()

Notice how I overrode the "virtual" method speak() in Dog and Cat
and just for a change I left the parent method in place for Giraffe.

Does that answer your question?

-- Michael Chermside






More information about the Python-list mailing list