Conflicting needs for __init__ method

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


On 1/15/07, Ben Finney <bignose+hates-spam at benfinney.id.au> wrote:
> The alternate constructors are decorated as '@classmethod' since they
> won't be called as instance methods, but rather:
>
>     foo = Rational.from_string("355/113")
>     bar = Rational.from_int(17)
>     baz = Rational.from_rational(foo)

I agree with you that that method is the right approach. But you can
also use module level functions, and sometimes that is even better:

def from_string(str):
    (n, d) = parse_elements_of_string_input(str)
    return Rational(n, d)

That way, you do not even have to expose the class at all to users of
the module. I think it depends on how you want users to use your
module. If you prefer:

import rational
rat = rational.from_string("123/456")

Then module level functions is best. But if you prefer:

from rational import Rational
rat = Rational.from_string("123/456")

class methods are better.

-- 
mvh Björn



More information about the Python-list mailing list