7.11 Class variables
An instance variable is unique to each object created by a class. A class
variable is shared, accessible, and changeable by all objects of a class. There are
similarities with the global variables we saw in section
6.9.2. Coders frequently use class variables instead of top level global variables.
Restricting their use within a class is more acceptable, especially if their names start with
“__
”.
As we have seen, if obj
is the name of an instance, you reference an instance
variable with a name prefixed by “obj.
”. obj
is often
self
.
You define a class variable at the top level of a class, along with the instance methods.
class Guitar:
number_of_guitars = 0
def __init__(self, brand):
Guitar.number_of_guitars += 1
plural = "s" if Guitar.number_of_guitars != 1 else ""
print(f"We have {Guitar.number_of_guitars...