More __init__ methods
Duncan Booth
duncan.booth at invalid.invalid
Fri Nov 7 10:16:29 EST 2008
Mr.SpOOn <mr.spoon21 at gmail.com> wrote:
> Now I must pass a and b to the main constructor and calculate them in
> the classmethods.
>
> class foo:
> def __init__(self, a, b):
> self.a = a
> self.b = b
>
> @classmethod
> def from_string(self, ..):
> ...
> ...
>
> What I mean is: I can't use anymore __init__ as the default
> constructor, but I always have to specify the way I'm creating my
> object. Am I right? I'm asking just to be sure I have understood.
There is a really big advantage to being explicit in this situation: you no
longer have to make sure that all your constructors use a unique set of
types. Consider:
class Location(object):
def __init__(self, lat, long): ...
@classmethod
def from_city(name): ...
@classmethod
def from_postcode(name): ...
'from_string' is a bad name here for your factory method: you should try to
make it clear what sort of string is expected.
--
Duncan Booth http://kupuguy.blogspot.com
More information about the Python-list
mailing list