idiom for initialising variables

Trent Mick trentm at ActiveState.com
Wed Nov 6 14:06:52 EST 2002


[Rob Hall wrote]
> I'm just wondering on the correct python idiom for initialising variables.
> I see some code like this:
> 
> class myClass:
>     self.a = 1
>     def __init__(self):
>         ...more stuff here
> 

I suspect you quoted that one incorrectly. It should be:
    class myClass:
        a = 1
        def __init__(self):
            ...more stuff here

> I also see:
> 
> class myClass
>     def __init__(self):
>         self.a = 1
>         ...more stuff here
> 
> 
> Which is the correct idiom?  or is there a subtle difference I am missing?

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.

    >>> 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'
    >>>


Trent

-- 
Trent Mick
TrentM at ActiveState.com




More information about the Python-list mailing list