Lab Check-in 4: OOP
Check-in questions and answers will be available after lab solutions are released.
Selfie
Q1: A-Okay
Note for Academic Interns: be sure to ask the student not just what happens, but why it happens.
>>> class A:
... y = 1
... def __init__(self, y):
... self.y = y
... def f(self, x):
... self.y += x
...
>>> a = A(0) # Ok or not okay?
______Okay
>>> a.f(6) # Ok or not okay?
______Okay
>>> a.f(A, 9) # Ok or not okay?
______Not okay
>>> A.f(a, 4) # Ok or not okay?
______Okay
>>> A.f(A, 4) # Ok or not okay?
______Okay
Explanation:
Calling a method via an instance will pass in the instance itself implicitly as self
, so the third line tries to pass in three arguments to f
: a
, A
, and 9
(in that order). The last two lines are okay because calling a method via the class (i.e., non-instance) does not implicitly pass in anything as self
.
The last example is most likely to trip people up, if at all. Be sure to emphasize that self
is just a placeholder. You can pass in another object explicitly as self
and things will work just fine. The self
does not necessarily need to be bound to an instance of an object.