>>> class Robot():
brand1 = "Kuka"
>>> x = Robot()
>>> x.brand1 = "Luka"
I should say that classes don’t have attributes as such, but class variables which behave like attrbiutes. Every instance inherits the same one from the parent class, but can alter it at any time after instantiation. Once altered, it becomes an instance attribute, no longer tied to the parent.
To further add to the confusion,
>>> Robot.brand2 = "Marc"
Notice that we are able to instantly give every instance a new attribute just by giving it to the parent. I’m still kind of bent on the term “class variable” as opposed to “class attribute”, probably because it is necessary to keep a distinction between class and instances (in my own mind, perhaps).
Bottom line, if we give a new attribute to an instance, it is isolated to that instance. If we give a new attribute to the parent class, it immediately descends to all instances of that class. Each instance can alter it (make it an instance attribute) as needs be.
>>> x.brand3 = "Mica"
>>> Robot.brand3 = "Formica"
>>> y = Robot()
Notice that the earlier declared attribute on
x is unchanged when
Robot declares a variable of the same name? All other instances will be affected, though, unless they too have this attribute, already.
One final note… A class variable is excellent for initializing counters and other preset objects on instances that they can individually update. Recall that once an instance changes the value it becomes isolated to that instance.
Class variables are also useful for keeping a running count of, and/or identifying instances; i.e., giving every instance a unique id. This could not be done from a program line (on the fly), though. It would have to happen in the
__init__ method and would use a class method to do it, most likely.