First page Back Continue Last page Overview Graphics

Class Attributes

A class attribute is an attribute of the class (circular, I know), rather than an attribute of an instance of a class. They are shared by all the instances. Class attributes are defined out of the method definitions. Usually, they are positioned directly below the class header:

>>> class A: ... a = "I am a class attribute!" ... >>> x = A() >>> y = A() >>> x.a 'I am a class attribute!' >>> y.a 'I am a class attribute!' >>> A.a 'I am a class attribute!'

If you want to change the value of a Class attribute, it has to be done with ClassName.AttributeName and not with InstanceName.AttributeName.

>>> x.a = "This creates a new instance attribute for x!" >>> y.a 'I am a class attribute!' >>> A.a 'I am a class attribute!' >>> x.a 'This creates a new instance attribute for x!'