简体   繁体   中英

Correctly calling an instance method in a class

The statement that returns self.seconds.splitSeconds() is not working correctly, so guide me with the proper syntax

class Time:
    def convertToSeconds(self):
      self.minutes = self.hours * 60 + self.minutes
      self.seconds = self.minutes * 60 + self.seconds
      return self.seconds

    def splitSeconds(seconds):
      self.hours = seconds // 3600
      self.minutes = (seconds % 3600) // 60
      self.seconds = seconds % 60
      return self

    def increment(self, seconds):
      self.seconds = self.convertToSeconds() + seconds
      return self.seconds.splitSeconds()

    def printTime(time):
      print(str(time.hours)+":"+str(time.minutes)+":"+str(time.seconds))

 time = Time()
 time.hours = 11
 time.minutes = 30
 time.seconds = 45

 seconds = 40

 time.increment(seconds)
 time.printTime()

I believe you need to add self as an attribute to splitSeconds .

def splitSeconds(self, seconds)

Additionally, your return statement should be

return self.splitSeconds(self.seconds) # edited based on comments

You should invoke the instance method on the instance , not anything else.

You need __init__ to initialize your Time Class, like:

class Time:
    def __init__(self, hours, minutes, seconds):
        self.hours = hours
        self.minutes = minutes
        self.seconds = seconds

    def convertToSeconds(self):
      self.minutes = self.hours * 60 + self.minutes
      self.seconds = self.minutes * 60 + self.seconds
      return self.seconds

    def splitSeconds(self, seconds):
      self.hours = seconds // 3600
      self.minutes = (seconds % 3600) // 60
      self.seconds = seconds % 60


    def increment(self, seconds):
      self.seconds = self.convertToSeconds() + seconds
      return self.seconds

    def printTime(self):
      print(str(self.hours)+":"+str(self.minutes)+":"+str(self.seconds))

time = Time(11,30,45)

seconds = 40
time.increment(seconds)
time.printTime()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM