External Exam Download Resources Web Applications Games Recycle Bin

Class variables

class variables.py

class User:
  instances = 0 #Class variable
  def __init__(self, age=18):
      self.age = age
      User.instances += 1

steve = User() #using the default age parameter of 18 set in constructor
julie = User(23)
sarah = User(45)

print(steve.age) #18
print(sarah.age) #45
print(User.instances) #3 user instances total




note below - instances can take a copy of the Class variable, and if they do, it will become an instance (self) variable, e.g.:

steve.instances = User.instances
steve.instances = -1
print(User.instances, sarah.instances, steve.instances)
#prints 3 3 -1