polymorphism

Carl Banks imbosol at aerojockey.com
Tue May 13 01:14:35 EDT 2003


Alex wrote:
> Haris Bogdanovic wrote:
> 
>> How is polymorphism implemented in Python ?
>> Is there a substitution for C++ virtual functions ?
>> Can you give me a short example of how this works ?
>> 
>> Thanks
>> Haris
> 
> The short answer is every class method is virtual.  
> 
> The longer answer is that python is not statically typed.  This makes it
> *much* more flexible than C++.  If desired, polymorphism can be achieved
> withough any inheritance at all.  After a couple days, C++ will feel like a
> straight jacket.

Dude, you rule.  Mind if I use this simile?


> A simple example:
> 
> class Base:
>  def fnc(self):
>    print 'base'
>  def another_fnc(self):
>    self.fnc()
> 
> class Derived(Base):  # derives from Base
>  def fnc(self):
>    print 'derived'
> 
> b=Base()
> d=Derived()
> 
> b.another_fnc()  
> d.another_fnc()  
> 
> #outputs: 
> # base
> # derived

The replies so far have ignored one significant aspect of Python
polymorphism: unlike C++, it isn't tied to inheritance.  So, there is
no need to form class hierarchies just for the sake

If you want class A and class B to have the same interface, just write:

    class A:
        def f(self):
            print "class A"
    class B:
        def f(self):
            print "class B"

    def printclassname(obj):
        obj.f()

    a = A()
    printclassname(a)
    b = B()
    printclassname(b)

Even though a and b are instances of different classes that do not
share a common base (other than object), they can both be passed into
the printclassname function, and used identically.

As a practical matter, in Python, I recommend against building large
class hierarchies like you might do in C++.  With one Exception, use
inheritance in Python only when you really need to share some
functionality with a parent class, and not just mimic an interface.

(Pun intended.)


-- 
CARL BANKS




More information about the Python-list mailing list