[Tutor] overloaded methods

alan.gauld@bt.com alan.gauld@bt.com
Tue, 1 Jan 2002 18:51:28 -0000


> just to confirm. Overloading method names
> (with parameters belonging to different types)
> is not possible in python.

Thats right. The parameter is a name which could refer 
to any object.

> class Currency:
> 	pass
> class Dollar(Currency):
> 	pass
> class Euro(Currency):
> 	pass
> 
> class CalculateRupeeEquivalent:
> 	def calculate(currency):
> 		//type checking of curency here?
> 		//i don't like it with lots of ifs and else.

Neither do I, dictionary lookups are much nicer and faster.

> class CalculateRupeeEquivalentForDollar(CalculateRupeeEquivalent):
> 	def calculate(currency):
> 		//return equivalent

Still not reliable since you can't guarantee that currency 
is a dollar...

Better(IMHO) to stick to the original plan and create conversion
methods per currency. Then you can check the type by using the 
type itself as a key into a dictionary which points to the 
conversion functions, something like this:

currencyType == type(currency)
if convert.haskey(currencyType):   
    convert[currencyType]()

I suspect that only works in V2.2

If you prefer create a currencyType method in each 
currency class that returns a constant. 

(DOLLAR, EURO, RUPEE) = (1,2,3)

class Dollar(Currency):
    # ...
    def currencyType(): return DOLLAR

class RupeeConvertor:
   def dollarToRupee(self,currency): # do it here
   def euroToRupee(self, currency): # and here too

   def __init__(self):
      self.convertor = {DOLLAR:self.dollarToRupee,
                        EURO:self.euroToRupee }
   
   def convert(self, currency):
      if self.convertor.haskey(currency.currencyType):
          return self.convertor[currency.currencyType](currency) 

Err, something like that anyway...

OTOH surely most currency conversions involve a single 
conversion value(the exchange rate) so couldn't you just 
get the currencyType dictionary populated with the rates?
Then only one convertion function is needed.

Alan G