Function override?
Justin Sheehy
dworkin at ccs.neu.edu
Thu Mar 30 16:24:22 EST 2000
Arinté <jamarijr at hotmail.com> writes:
> I have a class similar to this:
>
> class over:
> somefun(self, bakeint):
> ...
> somefun(self, bakeStr):
>
> If the user uses a string then I want to use the 2nd one, else an
> Integer then use the 1st one?
>
> How can I get this?
There are plenty of ways. Here's a trivial one:
>>> class polym:
... def somefun_int(self, bakeint):
... print '%s is an int' % bakeint
... def somefun_str(self, bakeStr):
... print '%s is a string' % bakeStr
... def somefun(self, arg):
... if type(arg) == type(1):
... self.somefun_int(arg)
... elif type(arg) == type(''):
... self.somefun_str(arg)
... else:
... print "Don't know what to do with %s" % arg
...
>>> p = polym()
>>> p.somefun(42)
42 is an int
>>> p.somefun("spam")
spam is a string
> And what is this call in c, the word escapes me right now.
It's called polymorphism, regardless of the implementation language.
C++ refers to this variety of polymorphism as "method overloading".
-Justin
More information about the Python-list
mailing list