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.
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:
Note that this isn't the case for mutable attributes, however. Mutable attributes are shared if theyre part of a class definition.
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.