SV: Polymorphism using constructors
K Viltersten
tmp1 at viltersten.com
Tue Mar 4 15:00:23 EST 2008
"Carl Banks" <pavlovevidence at gmail.com> skrev i meddelandet
news:24adaf72-0c55-4a88-86d0-296363ead17f at s8g2000prg.googlegroups.com...
> 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).
OP understands and thanfully accepts
the suggestion.
--
Regards
Konrad Viltersten
--------------------------------
sleep - a substitute for coffee for the poor
ambition - lack of sense to be lazy
More information about the Python-list
mailing list