Python Class Instance Variables

Variables that a class defines using self can only be accessed through an instance of the class. Instance variables are created in the constructor (__init__ method) for the class.

Example

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

myClass = AttributeInstanceClass()
print(myClass.x)

Output

6

Class instance variables are specific to the instance of the class. ie. The value of the instance variable is not shared among all instances of the class (see class variables):

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

objectA = MyClass()
objectB = MyClass()

objectB.x = 13

print(objectA.x)
print(objectB.x)

Output

6
13

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

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

Notes

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