idiom for initialising variables

Fredrik Lundh fredrik at pythonware.com
Wed Nov 6 14:20:34 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

better make that:

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?

the first form creates a class attribute, the second an instance
attribute.

class attributes are shared between all instances of the class.

when referring to an attribute in an expression (e.g. self.a on the right
side of an assignment), Python looks for it in the instance first, and looks
in the class only if it cannot find the attribute in the instance.

when assigning to an attribute (e.g. self.a on the left side), Python
always updates the instance.

you can use class attributes...

...if you really want a shared attribute (careful with mutable objects)

...if you have a couple of attributes that are usually not changed, and you
want to save a little memory (very little) and effort.

    class myclass:
        buffersize = 16384 # default
        def setbuffersize(self, buffersize):
            self.buffersize = buffersize

...if you have attributes that you may want to override in a subclass:

    class mysubclass(myclass):
        buffersize = 131072

...if methods you've added in a subclass needs additional attributes, and
you don't want to override the __init__ method:

    class mysubclass(myclass):
        encoding = "utf-8"
        def read_encoded_data(self):
            return self.read(self.encoding)

</F>

<!-- (the eff-bot guide to) the python standard library:
http://www.pythonware.com/people/fredrik/librarybook.htm
-->





More information about the Python-list mailing list