osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Which part of the loop is it going through in this class frame?


On 3/7/2018 4:57 PM, C W wrote:
> Hello,
> 
> I am new to OOP. I'm a bit confused about the following code.
> 
> class Clock(object):
>      def __init__(self, time):
>          self.time = time
>      def print_time(self):
>          time = '6:30'
>          print(self.time)

Local name 'time' is bound to '6:30'.
Attribute 'time' of the 'self' instance is bound to '5:30' because of 
the call and initization.  You asked to print the latter.  If you write 
'print(time)' you will see '6:30'.

> clock = Clock('5:30')
> clock.print_time()
> 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?
> 
> 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(), if so,
> why don't I just set self.time = '6:30' instead of self.time = time?
> 
> Thanks!
> 


-- 
Terry Jan Reedy