Python Polymorphism
Fredrik Lundh
fredrik at pythonware.com
Thu May 12 16:56:01 EDT 2005
Carlos Moreira wrote:
> Supose that I want to create two methos (inside a
> class) with exactly same name, but number of
> parameters different:
that's known as multimethods, or multiple dispatch. it's a kind of
polymorphism; it's not the only way to do it, nor is it the only thing
that qualifies as polymorphism.
(in OO lingo, polymorphism usually means that a variable can hold
objects of different types/classes, and that the language can per-
form a given operation on an object without having to know in ad-
vance what type/class it belongs to).
Python only supports single-dispatch in itself, but you can use the
existing mechanisms to implement multimethods in different ways.
for some ways to do it, see:
http://www.artima.com/weblogs/viewpost.jsp?thread=101605
http://www-106.ibm.com/developerworks/library/l-pydisp.html
however, solving your problem is of course trivial; just change
> class myClass:
> myAttribute = 0
> def myMethod(self):
> self.myAttribute += 1
> def myMethod(self, myValue):
> self.myAttribute += myValue
to
class myClass:
myAttribute = 0
def myMethod(self, myValue=1):
self.myAttribute += myValue
and you're done.
> I want to use the power of polymorphism to modelate
> the problem.
the problem you described can be trivially solved with a default
argument. maybe you should come up with a more realistic pro-
blem?
</F>
More information about the Python-list
mailing list