@@ -337,6 +337,77 @@ object and the argument list, and the function object is called with this new
337337argument list.
338338
339339
340+ .. _tut-class-and-instance-variables :
341+
342+ Class and Instance Variables
343+ ----------------------------
344+
345+ Generally speaking, instance variables are for data unique to each instance
346+ and class variables are for attributes and methods shared by all instances
347+ of the class::
348+
349+ class Dog:
350+
351+ kind = 'canine' # class variable shared by all instances
352+
353+ def __init__(self, name):
354+ self.name = name # instance variable unique to each instance
355+
356+ >>> d = Dog('Fido')
357+ >>> e = Dog('Buddy')
358+ >>> d.kind # shared by all dogs
359+ 'canine'
360+ >>> e.kind # shared by all dogs
361+ 'canine'
362+ >>> d.name # unique to d
363+ 'Fido'
364+ >>> e.name # unique to e
365+ 'Buddy'
366+
367+ As discussed in :ref: `tut-object `, shared data can have possibly surprising
368+ effects with involving :term: `mutable ` objects such as lists and dictionaries.
369+ For example, the *tricks * list in the following code should not be used as a
370+ class variable because just a single list would be shared by all *Dog *
371+ instances::
372+
373+ class Dog:
374+
375+ tricks = [] # mistaken use of a class variable
376+
377+ def __init__(self, name):
378+ self.name = name
379+
380+ def add_trick(self, trick):
381+ self.tricks.append(trick)
382+
383+ >>> d = Dog('Fido')
384+ >>> e = Dog('Buddy')
385+ >>> d.add_trick('roll over')
386+ >>> e.add_trick('play dead')
387+ >>> d.tricks # unexpectedly shared by all dogs
388+ ['roll over', 'play dead']
389+
390+ Correct design of the class should use an instance variable instead::
391+
392+ class Dog:
393+
394+ def __init__(self, name):
395+ self.name = name
396+ self.tricks = [] # creates a new empty list for each dog
397+
398+ def add_trick(self, trick):
399+ self.tricks.append(trick)
400+
401+ >>> d = Dog('Fido')
402+ >>> e = Dog('Buddy')
403+ >>> d.add_trick('roll over')
404+ >>> e.add_trick('play dead')
405+ >>> d.tricks
406+ ['roll over']
407+ >>> e.tricks
408+ ['play dead']
409+
410+
340411.. _tut-remarks :
341412
342413Random Remarks
0 commit comments