When defining a class, you can create a variable inside a class. This becomes a class attribute.
>>> class A: ... foo = 1
A class attributed can be accessed and assigned to just like an attribute of an object. (A class is an object too!)
>>> A.foo 1 >>> A.foo = 10 >>> A.foo 10
A class attribute can be useful when you want to have one variable that all the instances of the class can access.
For example, the following class has attribute count
, which is equal to the number of instances created so far. Each instance use count to get its order of creation.
>>> class B: ... count = 0 ... def __init__(self): ... self.__class__.count += 1 ... self.order = self.__class__.count ... >>> class B: ... count = 0 ... def __init__(self): ... self.__class__.count += 1 ... self.order = self.__class__.count ... >>> foo = B() >>> foo.order 1 >>> B.count 1 >>> bar = B() >>> bar.order 2 >>> B.count 2 >>> B() <__main__.B instance at 0x403490> >>> B.count 3