summaryrefslogtreecommitdiffstats
path: root/Doc/tutorial
diff options
context:
space:
mode:
authorRaymond Hettinger <python@rcn.com>2014-06-24 20:03:54 (GMT)
committerRaymond Hettinger <python@rcn.com>2014-06-24 20:03:54 (GMT)
commitc03dc0f164d468f87509675c727ac6e6322264c7 (patch)
tree3af1c1d38bf66f96ab411c5c04e55f727419b8e4 /Doc/tutorial
parentf5c5175b47c150966456835ce5c05c6271330562 (diff)
parent4c945fe9e9ea813ecb19ed705e1c7b3ae26b0d2a (diff)
downloadcpython-c03dc0f164d468f87509675c727ac6e6322264c7.zip
cpython-c03dc0f164d468f87509675c727ac6e6322264c7.tar.gz
cpython-c03dc0f164d468f87509675c727ac6e6322264c7.tar.bz2
merge
Diffstat (limited to 'Doc/tutorial')
-rw-r--r--Doc/tutorial/classes.rst71
1 files changed, 71 insertions, 0 deletions
diff --git a/Doc/tutorial/classes.rst b/Doc/tutorial/classes.rst
index 08072a3..6c71d80 100644
--- a/Doc/tutorial/classes.rst
+++ b/Doc/tutorial/classes.rst
@@ -387,6 +387,77 @@ object and the argument list, and the function object is called with this new
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::
+
+ 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'
+
+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::
+
+ class Dog:
+
+ tricks = [] # mistaken use of a class variable
+
+ def __init__(self, name):
+ self.name = name
+
+ def add_trick(self, trick):
+ self.tricks.append(trick)
+
+ >>> d = Dog('Fido')
+ >>> e = Dog('Buddy')
+ >>> d.add_trick('roll over')
+ >>> e.add_trick('play dead')
+ >>> d.tricks # unexpectedly shared by all dogs
+ ['roll over', 'play dead']
+
+Correct design of the class should use an instance variable instead::
+
+ class Dog:
+
+ def __init__(self, name):
+ self.name = name
+ self.tricks = [] # creates a new empty list for each dog
+
+ def add_trick(self, trick):
+ self.tricks.append(trick)
+
+ >>> d = Dog('Fido')
+ >>> e = Dog('Buddy')
+ >>> d.add_trick('roll over')
+ >>> e.add_trick('play dead')
+ >>> d.tricks
+ ['roll over']
+ >>> e.tricks
+ ['play dead']
+
+
.. _tut-remarks:
Random Remarks