Class Instance Attributes

Variables that a class defines using "self" can only be accessed through an instance of the class are usually created in the constructor for the class.

Example

Python
class AttributeInstanceClass():
    def __init__(self):
        self.x = 6

myClass = AttributeInstanceClass()
print(myClass.x)

Output

6

As with class attributes, class instance attributes are specific to the instance of the class:

Python
class AttributeInstanceClass():
    def __init__(self):
        self.x = 6

myClass1 = AttributeInstanceClass()
myClass2 = AttributeInstanceClass()
myClass2.x = 13
print(myClass1.x)
print(myClass2.x)

Output

6
13

If you try to reference an instance attribute as if it were a class attribute, Python will tell you:

Python
  File "test.py", line 53, in <module>
    print(AttributeInstanceClass.x)
AttributeError: type object 'AttributeInstanceClass' has no attribute 'x'

Notes

What Python calls an "instance attribute" is often called a "field" in other languages.