Conflicting needs for __init__ method
BJörn Lindqvist
bjourne at gmail.com
Wed Jan 17 04:03:46 EST 2007
On 1/16/07, Ben Finney <bignose+hates-spam at benfinney.id.au> wrote:
> "BJörn Lindqvist" <bjourne at gmail.com> writes:
>
> > import rational
> > rational.rational(45)
> > rational.rational(45.0)
> > rational.rational([45, 45.5])
> >
> > def rational(obj):
> > initers = [(int, from_int), (basestring, from_str), (list, from_list)]
> > for obj_type, initer in initers:
> > if isinstance(obj, obj_type):
> > return initer(obj)
> > raise ValueError("Can not create a rational from a %r" % type(obj).__name__)
>
> You've just broken polymorphism. I can't use your factory function
> with an instance of my custom type that behaves like a list, but is
> not derived from list (or a non-'int' int, or a non-'basestring'
> string).
Indeed, but I do not think that is fatal. There are many functions in
Pythons stdlib that breaks duck typing exactly like that.
> Use the supplied value as you expect to be able to use it, and catch
> the exception (somewhere) if it doesn't work. That will allow *any*
> type that exhibits the correct behaviour, without needlessly
> restricting it to a particular inheritance.
Can you show an example of that? It seems like that approach would
lead to some very convoluted code.
--
mvh Björn
More information about the Python-list
mailing list