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

Frank Millman frank at chagford.com
Wed Mar 7 23:48:20 EST 2018


"C W"  wrote in message 
news:CAE2FW2nuDJcmvuKAvZH01TrKqEENtkDXDPBAWcPHHsgx8jVLVA at mail.gmail.com...
>
> 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)
>
> 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?
>

In print_time(), the variable 'time' is not the same as the variable 
'self.time'.

'time', a local variable, is set to '6:30'.

'self.time', an instance variable, is set to '5:30'.

You printed self.time, hence the result.

Frank Millman





More information about the Python-list mailing list