Method overloading?

Grant Edwards grante at visi.com
Thu Feb 15 10:53:07 EST 2007


On 2007-02-15, placid <Bulkan at gmail.com> wrote:

>> > Is it possible to be able to do the following in Python?
>>
>> > class Test:
>> >     def __init__(self):
>> >         pass
>>
>> >     def puts(self, str):
>> >         print str
>>
>> >     def puts(self, str,str2):
>> >         print str,str2
>>
>> > if __name__ == "__main__":
>> >     t = Test()
>> >     t.puts("hi")
>> >     t.puts("hi","hello")
>>
>> You tell us: what happened when you tried it?
>
> Well, when i run it i get this error "puts() takes exactly 3 arguments
> (2 given)" which means that the second a time i try to define the
> puts() method "overwrites" the first one

Correct.  That means it's not possible to do what you wrote.

>> And then what happens when you do this?
>>
>> class Test:
>>     def __init__(self):
>>         pass
>>
>>     def puts(self, *args):
>>         print ' '.join(args)
>>
>> if __name__ == "__main__":
>>     t = Test()
>>     t.puts("hi")
>>     t.puts("hi","hello")
>
> but this isn't overloading.

No, it isn't.  [You can't overload methods in Python.  Was that
your question?] It is, however, the way one does what you
appear to be trying to do.

-- 
Grant Edwards                   grante             Yow!  If I am elected no
                                  at               one will ever have to do
                               visi.com            their laundry again!



More information about the Python-list mailing list