Posts
read more
Python Class and Instance Variables Explained
Python Instance and Class Variables
Call me late to the game, but TIL about Python instance and class variables the hard way. I was setting up multiple classes using composition and was left wondering why, when storing data in a list of class instances, the data was shared across all instances.
As specified 9.3.5. Class and Instance Variables
class Dog:
kind = 'canine' # class variable shared by all instances
def __init__(self, name):
self.name = name # instance variable unique to each instance
>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> d.kind # shared by all dogs
'canine'
>>> e.kind # shared by all dogs
'canine'
>>> d.name # unique to d
'Fido'
>>> e.name # unique to e
'Buddy'For example, the tricks list in the following code should not be used as a class variable because just a single list would be shared by all Dog instances: