Credit: Sébastien Keim, Troy Melhase, Peter Cogolo
You want to set some attributes to constant values,
during object initialization, without forcing your subclasses to call
_ _init_ _ method.
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 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.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, ...