class Counter(object): count = 99 # count is a class variable def __init__(self,c): self.count = c # self.count is an instance variable def inc(self): self.count = self.count + 1 def __str__(self): return '(count: ' + str(self.count) + ')' c1 = Counter(0) c2 = Counter(-99) for i in range(1000): c1.inc() c2.inc() print('c1 is ' + str(c1)) print('c2 is ' + str(c2)) print('Counter.count is ' + str(Counter.count)) """ If we do not need to use the class variable, we can/should get rid of the class variable. """ class Counter(object): def __init__(self,c): self.count = c # self.count is an instance variable def inc(self): self.count = self.count + 1 def __str__(self): return '(count: ' + str(self.count) + ')' c1 = Counter(0) c2 = Counter(-99) for i in range(1000): c1.inc() c2.inc() print('c1 is ' + str(c1)) print('c2 is ' + str(c2)) """ Instance variables should be defined inside the __init__ method. If instance variables are defined out of the __init__ method, Python complains it. """ """ class Counter(object): self.count = 99 # this causes the following: NameError: name 'self' is not defined def inc(self): self.count = self.count + 1 def __str__(self): return '(count: ' + str(self.count) + ')' """