idiom for initialising variables

Trent Mick trentm at ActiveState.com
Wed Nov 6 14:29:07 EST 2002


[Trent Mick wrote]
> Either works. Which one you chose probably depends more on your
> preference for aethetics than anything else. There *is* a slight
> difference in when the 'a' variable gets created. With the former, you
> can access 'a' on the class object. With the latter you have to create a
> class instance (i.e. the __init__() method has to run) before 'a' is
> available.

Despite having a response that looks almost exactly like mine, Erik's
response reveals a difference that I didn't really identify: that 'a' in
the former case ("TopLevel" in my example) is shared by all instances.
So, to continue my example code:

> 
>     >>> class TopLevel:
>     ...     a = 1
>     ...     def __init__(self):
>     ...             pass
>     ...
>     >>> class InInit:
>     ...     def __init__(self):
>     ...             self.a = 1
>     ...
>     >>>
>     >>>
>     >>> t = TopLevel()
>     >>> t.a
>     1
>     >>> i = InInit()
>     >>> i.a
>     1
>     >>>
>     >>> TopLevel.a
>     1
>     >>> InInit.a
>     Traceback (most recent call last):
>       File "<stdin>", line 1, in ?
>     AttributeError: class InInit has no attribute 'a'
>     >>>

    >>> t = TopLevel()
    >>> t.a
    1
    >>>
    >>> TopLevel.a
    1
    >>> TopLevel.a = 42
    >>> t.a
    42
    >>>


not-quite-as-swift-as-erik-ly yours,
Trent


-- 
Trent Mick
TrentM at ActiveState.com




More information about the Python-list mailing list