[Tutor] Re: Tutor digest, Vol 1 #1302 - 15 msgs
Mon, 31 Dec 2001 10:20:43 -0800
> Message: 9
> From: Karthik Gurumurthy <email@example.com>
> To: firstname.lastname@example.org
> Date: Mon, 31 Dec 2001 19:20:50 +0530
> Subject: [Tutor] overloaded methods
> just to confirm. Overloading method names(with parameters belonging to
> different types)
> is not possible in python.
> class Currency:
> class Dollar(Currency):
> class Euro(Currency):
> class CalculateRupeeEquivalent:
> def calculate(currency):
> //type checking of curency here?
> //i don't like it with lots of ifs and else.
Well, it *is* possible to get the name of an object's class...
>>> class A:
>>> class B(A):
>>> a = A()
>>> b = B()
__main__ would of course be replaced by whatever your module name is, but in any case the final component
should be the classname. So you set up a dictionary that contains your conversion rates, and then do
# Get the part of the __class__ after the last period--
currencytype = str(currencyobject.__class__).split('.')[-1]
conversionrate = ConversionDict[currencytype]
return (currencyobject.amount * conversionrate)
Actually, I think that a better approach would be to build conversions into each currency class, and then
simply query the currency object.
return self.amount * self.rupeerate
rupeerate = 2.5
rupeerate = 3.0
(Obviously I'm just randomly guessing at conversion rates, as I have honestly no idea what the relative
value of the Rupee is ;) ) Depending on your application, you may want to import the actual values for the
conversion rates from somewhere else (so that they can be, for example, automatically updated from a