Method overloading?

Steven D'Aprano steve at REMOVEME.cybersource.com.au
Thu Feb 15 01:11:05 EST 2007


On Wed, 14 Feb 2007 21:12:39 -0800, placid wrote:

> On Feb 15, 4:04 pm, Grant Edwards <gra... at visi.com> wrote:
>> On 2007-02-15, placid <Bul... 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

Yes, that's right. It is no different from doing this:

x = 1
x = 2


>> 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.

Neither was your first example.


This is an example of overloading:

class Cheese(object):
    def flavour(self):
        return "tasty and scrumptious"
    def colour(self):
        return "yellow"


Now we define a sub-class which overloads some methods:

class BlueVein(Cheese):
    def colour(self):
        return "white with blue veins"

Testing it:


>>> c = BlueVein()
>>> c.flavour()  # inherited from the super class
'tasty and scrumptious'
>>> c.colour()  # over-ridden by the sub-class
'white with blue veins'
>>> super(BlueVein, c).colour()  # call the super class method
'yellow'


I hope this helps.



-- 
Steven D'Aprano 




More information about the Python-list mailing list