[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 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')

"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 

  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.

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