polymorphism

Alex delete.this.part.alex.news at attbi.com
Mon May 12 23:31:41 EDT 2003


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.

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


#################
# Another, more complex, example 
# don't try in C++

def add(a,b):
  return a+b

def square(a,b):
  return a**b

class A:
  def __str__(self):
    return 'aaa'

def myfunc(a,b):
  return str(a)+str(b)

seq=(('abc','def',add),(2,6,add),(2,6,square), (A(),'viola',myfunc))
for op1, op2, fnc in seq:
  print fnc(op1, op2)

# outputs:
# abcdef
# 8
# 64
# aaaviola


That may be a bit hard to parse for someone who is not familiar with python. 
I created a sequence of items.  Each item contained two operands and an
operator.  I applied the operator to the operands and printed the results. 
In this short example, functions, functions operands, and a class are all
being treated in a polymorphic fasion.  The example is obviously contrived,
however, hopefully it will give you some sense of the power and flexibility
of python.

Alex













More information about the Python-list mailing list