[Tutor] Re: Tutor digest, Vol 1 #1302 - 15 msgs

Jeff Shannon jeff@ccvcorp.com
Mon, 31 Dec 2001 10:20:43 -0800

> Message: 9
> From: Karthik Gurumurthy <karthikg@aztec.soft.net>
> To: tutor@python.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:
>         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.

Well, it *is* possible to get the name of an object's class...

>>> class A:
...  pass
>>> class B(A):
...  pass
>>> a = A()
>>> b = B()
>>> str(a.__class__)
>>> str(b.__class__)

__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
something like:

def ConvertToRupees(currencyobject):
    # 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.

class Currency:
    def ConvertToRupees(self):
        return self.amount * self.rupeerate

class Dollar(Currency):
    rupeerate = 2.5

class Euro(Currency):
    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

Jeff Shannon
Credit International