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.
class AttributeInstanceClass(): def __init__(self): self.x = 6 myClass = AttributeInstanceClass() print(myClass.x)
As with class attributes, class instance attributes are specific to the instance of the class:
class AttributeInstanceClass(): def __init__(self): self.x = 6 myClass1 = AttributeInstanceClass() myClass2 = AttributeInstanceClass() myClass2.x = 13 print(myClass1.x) print(myClass2.x)
If you try to reference an instance attribute as if it were a class attribute, Python will tell you:
File "test.py", line 53, in <module> print(AttributeInstanceClass.x) AttributeError: type object 'AttributeInstanceClass' has no attribute 'x'
What Python calls an "instance attribute" is often called a "field" in other languages.