O'Reilly logo

Python Cookbook, 2nd Edition by David Ascher, Anna Ravenscroft, Alex Martelli

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

20.14. Automatic Initialization of Instance Attributes

Credit: Sébastien Keim, Troy Melhase, Peter Cogolo

Problem

You want to set some attributes to constant values, during object initialization, without forcing your subclasses to call your _ _init_ _ method.

Solution

For constant values of immutable types, you can just set them in the class. For example, instead of the natural looking:

class counter(object):
    def _ _init_ _(self):
        self.count = 0
    def increase(self, addend=1):
        self.count += addend

you can code:

class counter(object):
    count = 0
    def increase(self, addend=1):
        self.count += addend

This style works because self.count += addend, when self.count belongs to an immutable type, is exactly equivalent to self.count = self.count + addend. The first time this code executes for a particular instance self, self.count is not yet initialized as a per-instance attribute, so the per-class attribute is used, on the right of the equal sign (=); but the per-instance attribute is nevertheless the one assigned to (on the left of the sign). Any further use, once the per-instance attribute has been initialized in this way, gets or sets the per-instance attribute.

This style does not work for values of mutable types, such as lists or dictionaries. Coding this way would then result in all instances of the class sharing the same mutable-type object as their attribute. However, a custom descriptor works fine:

class auto_attr(object): def _ _init_ _(self, name, factory, *a, **k): self.data = name, factory, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required