Skip to content

Commit d05478d

Browse files
authored
Merge pull request #75 from braboj/codex/add-header-summarizing-class-vs-instance-variables
Add docstring header explaining class vs instance variables
2 parents 7e7349f + ff66122 commit d05478d

1 file changed

Lines changed: 25 additions & 9 deletions

File tree

examples/08_classes/class_variables_pitfalls.py

Lines changed: 25 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,28 @@
1-
"""
2-
The statement self.<variable> may refer to two things at different times. When no instance
3-
variable exists for a name, Python will look up the variable in the class. So the value retrieved
4-
for self.<variable> will be the class variable.
5-
6-
But when setting an attribute via self, Python will always set an instance variable. So now
7-
self.<variable> is a new instance variable whose value is equal to the class variable + 1. This
8-
attribute shadows the class attribute, which you can no longer access via self but only via the
9-
class.
1+
"""Class vs. Instance Variables
2+
--------------------------------
3+
Class variables are shared by all instances, while instance variables belong
4+
to each object. Assigning to ``self.variable`` creates an instance attribute.
5+
If a class attribute with the same name exists, the instance attribute hides it
6+
and later reads through ``self`` return the instance value. Mixing them can be
7+
confusing because updates seem to apply only to some objects.
8+
9+
When you read ``self.value`` and ``value`` is not defined on the instance,
10+
Python falls back to the class attribute:
11+
12+
class A:
13+
value = 1
14+
15+
obj = A()
16+
print(obj.value) # 1 from the class
17+
18+
Any assignment using ``self`` stores a value on the instance:
19+
20+
obj.value = 2
21+
print(A.value) # 1
22+
print(obj.value) # 2
23+
24+
Here ``obj.value`` now shadows ``A.value``. To access the class attribute
25+
explicitly you must use ``A.value``.
1026
"""
1127

1228

0 commit comments

Comments
 (0)