Welcome, guest | Sign In | My Account | Store | Cart

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

Python, 18 lines
 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

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.

2 comments

Troy Melhase 19 years, 1 month ago  # | flag

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.

Sébastien Keim (author) 19 years, 1 month ago  # | flag

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

Created by Sébastien Keim on Mon, 14 Oct 2002 (PSF)
Python recipes (4591)
Sébastien Keim's recipes (24)

Required Modules

  • (none specified)

Other Information and Tasks