problems with class initiation

Steve Holden sholden at holdenweb.com
Sun Jul 1 16:29:19 EDT 2001


"Magnus Lie Hetland" <mlh at idi.ntnu.no> wrote ...
> "Iñigo Serna" <inigoserna at terra.es> wrote ...
> [snip]
> > I suppose the error comes due to Main class hasn't finished its
> > initiation when 'app.prefs.a' is executed so app is None in that moment.
>
> The assignment isn't finished, so app is indeed None. Instead of
> relying on global variables, you should supply app as a parameter
> to the constructor of Second, IMO... Thus:
>
> class Second:
>     def __init__(self, app):
>         return self.init_fn(app)
>     def init_fn(self, app):
>         return app.prefs.a
>
Note also that there is no logical reason why the "__init__()" method should
be returning something. AS far as I know, nothing takes any notice of what
__init__() returns, and it's usual to omit a return statement (impying a
return value of None).

So there doesn't really seem to be any need here to split the initialization
of the Second objects into two parts.

As far as I can tell the Second class could equally well be defined as

class Second:
    pass

without the effect of the code being changed in any way. If __init__()
doesn't change self, and it doesn't call anything with side effects, I don't
think it does *anything*.


> class Main:
>     def __init__(self):
>         self.prefs = Preferences()
>         self.fns = []
>         self.fns.append(Second(self))
>
> ... or something like that. (The design seemed slightly confusing to me,
> but I think this should work, at least :)
>
It may well work, but the Secod object appended to Main's self.fns will have
no attributes other than those common to every class instance, so there
doesn't seem to be much point in its having an __init__() method in the
first place.

regards
 Steve
--
http://www.holdenweb.com/








More information about the Python-list mailing list