It seems that in Python, to declare a variable in a class, it is static (keeps its value in the next instances). What better way to get around this problem?
class Foo():
number = 0
def set(self):
self.number = 1
>>> foo = Foo()
>>> foo.number
0
>>> foo.set()
>>> foo.number
1
>>> new_foo = Foo()
>>> new_foo.number
1
Variables defined at the class level are indeed “static”, but I don’t think they work quite the way you think they do. There are 2 levels here which you need to worry about. There are attributes at the class level, and there are attributes at the instance level. Whenever you do
self.attribute = ...inside a method, you’re setting an attribute at the instance level. Whenever python looks up an attribute, it first looks at the instance level, if it doesn’t find the attribute, it looks at the class level.This can be a little confusing (especially if the attribute is a reference to a mutable object). consider:
As others have mentioned, if you want an attribute to be specific to an instance, just initialize it as an instance attribute in
__init__(usingself.attr = ...).__init__is a special method which is run whenever a class is initialized (with a few exceptions that we won’t discuss here).e.g.