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

Cameron Simpson cs at cskk.id.au
Fri Mar 9 01:33:08 EST 2018


On 08Mar2018 20:25, C W <tmrsg11 at gmail.com> wrote:
>Thank you guys, lots of great answers, very helpful. I got it!
>
>A follow-up question:
>
>How did the value of "object" get passed to "time"? Obviously, they have
>different names. How did Python make that connection?
>
>Code is below for convenience.
>
>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

"object" isn't really passed anywhere, except to your class construction of 
"Clock". It hasn't any relation to the name "time" at all.

In Python, all classes are subclasses (directly or not) of the base class 
called "object", and your class definition makes that explicit here:

  class Clock(object):

This defines your class as just like the "object" class, but with the following 
extra features, which you go on the define below it.

With "new style classes" (a Python notion, not something special about OOP in 
general) the "object" base class is implicit, so you could just as well have 
written:

  class Clock:

to achieve the same purpose.

Being a subclass of "object" gets you an assortment of methods immediately, 
such as __str__ and __repr__ (used to present a class as a string). You even 
get an __init__ for free, but the default does nothing and that is usually not 
what you need.

Cheers,
Cameron Simpson <cs at cskk.id.au> (formerly cs at zip.com.au)



More information about the Python-list mailing list