On Wednesday, March 7, 2018 at 1:58:33 PM UTC-8, C W wrote:
> I am new to OOP.
There are (at least) two purposes for classes:
1) To group together data and functions in a meaningful way. Functions which
are defined inside a class are called methods.
2) To allow the preservation of state when you exit a method.
>I'm a bit confused about the following code.
> class Clock(object):
> def __init__(self, time):
> self.time = time
Here you are binding SELF.time to the value you passed in using the name time.
The value of self.time is preserved when you leave the __init__ method, and
that value is accessible again later when you call other methods in your Clock
object. The local variable called time in __init__() will disappear when you
> def print_time(self):
> time = '6:30'
> clock = Clock('5:30')
> I set time to 6:30, but it's coming out to 5:30. I guess it's because I
> passed in 5:30, so, it's replaced?
No, time and self.time are two different variables. Your program is printing
self.time, which you defined when you created your Clock object. And honestly,
that's the more intuitive behavior for an object. Why create an object and
then not use its state?
> How does line-by-line execution run inside a frame? How does __init__ work?
> I understand you must have __init__. Is it run before print_time(),
Yes, __init__() is the first method that gets called when you create an
instance of a class. You don't name __init__() explicitly, because Python has
to construct the reference to self. You perform all of the initial setup of
your object in __init__().
> if so,
> why don't I just set self.time = '6:30' instead of self.time = time?
If you don't want to pass a time to a Clock when you create one, you could
hard-code self.time = "6:30" in __init__(). But again, your instincts are
correct and intuitive to me. You want a Clock object that you can set to a
user-defined time, when you create it.