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

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu Mar 8 06:30:36 EST 2018


On Wed, 07 Mar 2018 16:57:51 -0500, 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

Here you set the instance attribute "self.time".

>     def print_time(self):
>         time = '6:30'
>         print(self.time)

Here you set the local variable "time", which is completely unrelated to 
the attribute "self.time".

If you are used to languages where "foo" inside a method is a short-cut 
for "self.foo" or "this.foo", Python does not do that. Local variables 
and instance attributes are distinct concepts, and Python keeps them 
distinct.


> How does line-by-line execution run inside a frame? 

There isn't actually line-by-line execution as such, although it can be 
very similar. Before the interpreter runs Python code, it compiles it to 
byte-code, and then runs the byte-code. A single line of source code 
could result in any number of lines of byte code, from zero to an 
unlimited number. 

> How does __init__
> work? I understand you must have __init__. 

You understand wrongly then :-)

It is normal and common to have an __init__ method, but it is not 
compulsory. If your class doesn't need one, you don't need to write it.

The __init__ method is the initialiser. Think of it as very similar to 
the constructor in some other languages, and for now the differences 
aren't important. The usual purpose of the __init__ method is to 
initialise the instance and set any attributes needed.

> Is it run before print_time(),

The __init__ method is called once, when the instance is first created. 
So the short answer is, yes, it will run before print_time(). But only 
once.

> if so, why don't I just set self.time = '6:30' instead of
> self.time = time?

Because then every instance will be set to 6:30, instead of letting you 
set each instance to a different time.



-- 
Steve




More information about the Python-list mailing list