Conflicting needs for __init__ method

BJörn Lindqvist bjourne at gmail.com
Tue Jan 16 11:37:06 EST 2007


On 1/16/07, Steven D'Aprano <steve at removeme.cybersource.com.au> wrote:
> On Tue, 16 Jan 2007 08:54:09 +1100, Ben Finney wrote:
> Think of built-ins like str() and int(). I suggest that people would be
> *really* unhappy if we needed to do this:
>
> str.from_int(45)
> str.from_float(45.0)
> str.from_list([45, 45.5])
> etc.
>
> Why do you consider that Rationals are different from built-ins in this
> regard?

I would solve that with:

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__)

-- 
mvh Björn



More information about the Python-list mailing list