Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 04ba0bb

Browse files
committed
Issue #11974: Add tutorial section on class and instance variables
(Based on a patch from Renee Chu.)
1 parent c0f964f commit 04ba0bb

2 files changed

Lines changed: 72 additions & 0 deletions

File tree

Doc/tutorial/classes.rst

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -387,6 +387,77 @@ object and the argument list, and the function object is called with this new
387387
argument list.
388388

389389

390+
.. _tut-class-and-instance-variables:
391+
392+
Class and Instance Variables
393+
----------------------------
394+
395+
Generally speaking, instance variables are for data unique to each instance
396+
and class variables are for attributes and methods shared by all instances
397+
of the class::
398+
399+
class Dog:
400+
401+
kind = 'canine' # class variable shared by all instances
402+
403+
def __init__(self, name):
404+
self.name = name # instance variable unique to each instance
405+
406+
>>> d = Dog('Fido')
407+
>>> e = Dog('Buddy')
408+
>>> d.kind # shared by all dogs
409+
'canine'
410+
>>> e.kind # shared by all dogs
411+
'canine'
412+
>>> d.name # unique to d
413+
'Fido'
414+
>>> e.name # unique to e
415+
'Buddy'
416+
417+
As discussed in :ref:`tut-object`, shared data can have possibly surprising
418+
effects with involving :term:`mutable` objects such as lists and dictionaries.
419+
For example, the *tricks* list in the following code should not be used as a
420+
class variable because just a single list would be shared by all *Dog*
421+
instances::
422+
423+
class Dog:
424+
425+
tricks = [] # mistaken use of a class variable
426+
427+
def __init__(self, name):
428+
self.name = name
429+
430+
def add_trick(self, trick):
431+
self.tricks.append(trick)
432+
433+
>>> d = Dog('Fido')
434+
>>> e = Dog('Buddy')
435+
>>> d.add_trick('roll over')
436+
>>> e.add_trick('play dead')
437+
>>> d.tricks # unexpectedly shared by all dogs
438+
['roll over', 'play dead']
439+
440+
Correct design of the class should use an instance variable instead::
441+
442+
class Dog:
443+
444+
def __init__(self, name):
445+
self.name = name
446+
self.tricks = [] # creates a new empty list for each dog
447+
448+
def add_trick(self, trick):
449+
self.tricks.append(trick)
450+
451+
>>> d = Dog('Fido')
452+
>>> e = Dog('Buddy')
453+
>>> d.add_trick('roll over')
454+
>>> e.add_trick('play dead')
455+
>>> d.tricks
456+
['roll over']
457+
>>> e.tricks
458+
['play dead']
459+
460+
390461
.. _tut-remarks:
391462

392463
Random Remarks

Misc/ACKS

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -238,6 +238,7 @@ Matt Chisholm
238238
Lita Cho
239239
Anders Chrigström
240240
Tom Christiansen
241+
Renee Chu
241242
Vadim Chugunov
242243
Mauro Cicognini
243244
David Cinege

0 commit comments

Comments
 (0)