ActiveState Code

Recipe 156546: Initializing attributes to a constant value


You need to set some attributes to a constant value during object initialization.

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
# The natural approach would be to do initialization in the object 
# constructor:

class counter:
    def __init__(self):
        self.count = 0
    def next(self):
        self.count += 1
        return self.count


# But Python offer a terse and efficient alternative:

class counter:
    count = 0
    def next(self):
        self.count += 1
        return self.count

Discussion

Well nothing really difficult here.

The magic is that the "count=0" statement create a class-attribute which will be used as long as it isn't overridden by an instance attribute with the same name. This is what do the "self.count+=1" statement.

Comments

  1. 1. At 6:13 p.m. on 18 oct 2002, Troy Melhase said:

    Actually, There's a Subtle Difference. The class attribute is only referenced the first time an instance tries "self.counter+=1". From then on, the instance has its own "counter" attribute. Example:

    Python 2.2.1 (#1, Sep 10 2002, 08:31:39)
    [GCC 2.95.3 20010315 (release)] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> class X:
    ...     counter = 0
    ...     def op(self):
    ...             self.counter += 1
    ...
    >>> myx = X()
    >>> X.counter
    0
    >>> myx.op()
    >>> X.counter
    0
    >>> myx.counter
    1
    >>>
    

    Note that this isn't the case for mutable attributes, however. Mutable attributes are shared if they’re part of a class definition.

  2. 2. At 5:29 a.m. on 23 oct 2002, Sébastien Keim (the author) said:

    A potential pitfall. As Troy Melhase explain in the previous comment, the recipe can cause some subtle bugs if it is used without care for mutable data initialization. And so it's probably better to not use it at all with mutable data.

    This is rather similar to the problems raised by the use of mutable objects as default value for function parameters.

    http://www.python.org/doc/current/tut/node6.html#SECTION006710000000000000000

Sign in to comment