Conflicting needs for __init__ method
Ben Finney
bignose+hates-spam at benfinney.id.au
Tue Jan 16 17:11:21 EST 2007
"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).
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.
--
\ "This sentence contradicts itself -- no actually it doesn't." |
`\ -- Douglas Hofstadter |
_o__) |
Ben Finney
More information about the Python-list
mailing list