Re: Conflicting needs for __init__ method
"BJörn Lindqvist" <bjourne@gmail. comwrites:
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
"BJörn Lindqvist" <bjourne@gmail. comwrites:
import rational
rational.ration al(45)
rational.ration al(45.0)
rational.ration al([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).__nam e__)
rational.ration al(45)
rational.ration al(45.0)
rational.ration al([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).__nam e__)
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
Comment