Polymorphism using constructors

Raymond Hettinger python at rcn.com
Mon Mar 3 16:17:08 EST 2008


On Mar 3, 12:21 pm, "K Viltersten" <t... at viltersten.com> wrote:
> I'm writing a class for rational numbers
> and besides the most obvious constructor
>
>   def __init__ (self, nomin, denom):
>
> i also wish to have two supporting ones
>
>   def __init__ (self, integ):
>     self.__init__ (integ, 1)
>   def __init__ (self):
>     self.__init__ (0, 1)

For this particular use case, providing default arguments will
suffice:

class Fraction:
  def __init__(self, numerator=0, denomiator=1):
       ...

Since Python doesn't support having two methods with the same name,
the usual solution is to provide alternative constructors using
classmethod():

  @classmethod
  def from_decimal(cls, d)
        sign, digits, exp = d.as_tuple()
        digits = int(''.join(map(str, digits)))
        if sign:
            digits = -digits
        if exp >= 0:
            return cls(digits * 10 ** exp)
        return cls(digits, 10 ** -exp)


Raymond



More information about the Python-list mailing list