Polymorphism using constructors
castironpi at gmail.com
castironpi at gmail.com
Mon Mar 3 22:21:23 EST 2008
On Mar 3, 4:03 pm, Carl Banks <pavlovevide... at gmail.com> wrote:
> On Mar 3, 4:17 pm, Raymond Hettinger <pyt... at rcn.com> wrote:
>
> > 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)
>
> Note that even some of Python's built in types (dict *cough*)
> implement homemade function overloading.
>
> The OP wanted to write a constructor that could accept either a pair
> of integers or a rational, there would be a good precedent for it.
>
> However, I would advise the OP to use the constructor only for the
> most common arguments, and use classmethods for more obscure, less
> common arguments (such as decimal or even float).
>
> Carl Banks
Unless application indicates calling signature uniformity, hash type
to subclass or to class method.
More information about the Python-list
mailing list