cpython: 8e0b7393e921 (original) (raw)
Mercurial > cpython
changeset 91350:8e0b7393e921 2.7
Issue #11974: Add tutorial section on class and instance variables (Based on a patch from Renee Chu.) [#11974]
Raymond Hettinger python@rcn.com | |
---|---|
date | Mon, 23 Jun 2014 18:03:21 -0700 |
parents | e28004fb30c0 |
children | 8d963c7db507 |
files | Doc/tutorial/classes.rst Misc/ACKS |
diffstat | 2 files changed, 72 insertions(+), 0 deletions(-)[+] [-] Doc/tutorial/classes.rst 71 Misc/ACKS 1 |
line wrap: on
line diff
--- a/Doc/tutorial/classes.rst +++ b/Doc/tutorial/classes.rst @@ -337,6 +337,77 @@ object and the argument list, and the fu argument list. +.. _tut-class-and-instance-variables: + +Class and Instance Variables +---------------------------- + +Generally speaking, instance variables are for data unique to each instance +and class variables are for attributes and methods shared by all instances +of the class:: +
kind = 'canine' # class variable shared by all instances[](#l1.18)
def __init__(self, name):[](#l1.20)
self.name = name # instance variable unique to each instance[](#l1.21)
+
+As discussed in :ref:tut-object
, shared data can have possibly surprising
+effects with involving :term:mutable
objects such as lists and dictionaries.
+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::
+
tricks = [] # mistaken use of a class variable[](#l1.42)
def __init__(self, name):[](#l1.44)
self.name = name[](#l1.45)
def add_trick(self, trick):[](#l1.47)
self.tricks.append(trick)[](#l1.48)
+ +Correct design of the class should use an instance variable instead:: +
def __init__(self, name):[](#l1.61)
self.name = name[](#l1.62)
self.tricks = [] # creates a new empty list for each dog[](#l1.63)
def add_trick(self, trick):[](#l1.65)
self.tricks.append(trick)[](#l1.66)
+ + .. _tut-remarks: Random Remarks
--- a/Misc/ACKS +++ b/Misc/ACKS @@ -235,6 +235,7 @@ Adal Chiriliuc Matt Chisholm Anders Chrigström Tom Christiansen +Renee Chu Vadim Chugunov Mauro Cicognini David Cinege