user12394113
user12394113

Reputation: 401

Correct usage of self in python instance

I have a class that I defined in the following way:

class Time:
    def print_time(self, am_pm):
        if am_pm == 'AM':
            tot_seconds = self.hour * 3600 + self.minute * 60 + self.second
        else: 
...         tot_seconds = self.hour * 3600 + self.minute * 60 + self.second + 12*3600.0
        print('%.2d:%.2d:%.2d' % (self.hour, self.minute, self.second))
        print('Seconds passed since midnight: ', tot_seconds)

I create an instance of Time with start = Time and then I specify the instance attributes as start.hour = 10, start.minute = 5, start.second = 2.

When I call the method print_time, if I do Time.print_time(start, 'AM') then I get the correct output. But if I try to pass start as self it does not work:

start.print_time('AM')
Traceback (most recent call last):

  File "<ipython-input-68-082a987f3007>", line 1, in <module>
    start.print_time('PM')

TypeError: print_time() missing 1 required positional argument: 'am_pm'

But why it is so? I thought that start would be the subject of the method invocation and so it would count as the first parameter and so I would need to specify only the am_pm parameter in print_time(). Why is this wrong?

Upvotes: 1

Views: 104

Answers (2)

welman ebimobowei
welman ebimobowei

Reputation: 29

class Time:

def __init__(self, am_pm, ):

    self.am_pm=am_pm

    self.hour=10

    self.minute=5

    self.second=2

def print_time(self):

    if self.am_pm=="AM":

        tot_seconds=self.hour * 3600 + self.minute * 60 + self.second

        print(tot_seconds)

    else:

        tot_seconds = self.hour * 3600 + self.minute * 60 + self.second + 12*3600.0

        print('%.2d:%.2d:%.2d' %(self.hour, self.minute, self.second))

        print( 'Seconds passed since midnight: ',tot_seconds)

start=Time("AM")

start.print_time()

except you change the object of the class ( start ) as self. ie

      self=Time("AM")
      self.print_time()

You can specify any object but not keywords

Upvotes: 0

Nate Norris
Nate Norris

Reputation: 996

start = Time does not actually construct an instance of your class. Rather, you assign the class definition Time to the variable start. You need open/close parentheses after a class name in order to construct an instance.

In other words, start.print_time() in your case is attempting to treat print_time like a static function -- as if you were simply calling Time.print_time() without an instance.

Hope that helps!

Upvotes: 3

Related Questions