Skip to content

Commit 22d3c40

Browse files
committed
adds bit about class variables
1 parent bd025d0 commit 22d3c40

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

classes-objects.ipynb

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,56 @@
181181
"print(higgs.roar)\n",
182182
"```\n",
183183
"\n",
184+
"::: {.content-visible when-format=\"html\"}\n",
185+
"::: aside \n",
186+
"Class variables can get a bit confusing; if you modify the variable associated with an object, it becomes an instance variable. For example:\n",
187+
"\n",
188+
"```python\n",
189+
"class Particle(object):\n",
190+
" spin = 0\n",
191+
"\n",
192+
" def init(self, charge, mass):\n",
193+
" self.charge = charge\n",
194+
" self.mass = mass\n",
195+
"```\n",
196+
"\n",
197+
"Here, `spin` is a class variable while `charge` and `mass` are instance variables. Creating two particles:\n",
198+
"```python\n",
199+
"p1 = Particle(1, 1)\n",
200+
"p2 = Particle(-1, 1)\n",
201+
"\n",
202+
"print(p1.spin)\n",
203+
"print(p2.spin)\n",
204+
"```\n",
205+
"\n",
206+
"we'll get\n",
207+
"```\n",
208+
"0\n",
209+
"0\n",
210+
"```\n",
211+
"\n",
212+
"If we change `spin` for `p1` only, it modifies the value just for that instance:\n",
213+
"```python\n",
214+
"p1.spin = 0.5\n",
215+
"print(p1.spin)\n",
216+
"print(p2.spin)\n",
217+
"```\n",
218+
"gives\n",
219+
"0.5\n",
220+
"0\n",
221+
"However, in general spin is still a class variable, and we can modify it for the whole class:\n",
222+
"Particle.spin = -0.5\n",
223+
"print(p1.spin)\n",
224+
"print(p2.spin)\n",
225+
"which gives\n",
226+
"0.5\n",
227+
"-0.5\n",
228+
"So for p1, spin has become an instance variable, but p2 is still pointing to the class variable.\n",
229+
"```\n",
230+
"\n",
231+
":::\n",
232+
":::\n",
233+
"\n",
184234
"## Instance variables\n",
185235
"\n",
186236
"::: {.fragment}\n",

0 commit comments

Comments
 (0)