Matt
Matt

Reputation: 41

Using a method will not change my object?

I made a method to add seconds to a time. For example, if I had one hour 15 minutes, and I used this function and added 15, the new object should read 1 hour 30 minutes. However, when I do currentTime.increment(10) in one line, then I print(currentTime) on the next line, what prints is the old currentTime, not updated.

I am new to classes so I do not know if they update like lists do. If I defined a list = [2,3,4] and I appended a new entry, it would edit the original list so I could print(list1) and it would be the old list with the new entry. Why does that not work here and why does it only work if I do it all in one step, like print(currentTime.increment(10)) ?

class MyTime:
    """ Create some time """

    def __init__(self,hrs = 0,mins = 0,sec = 0):
        """Splits up whole time into only seconds"""
        totalsecs = hrs*3600 + mins*60 + sec
        self.hours = totalsecs // 3600
        leftoversecs = totalsecs % 3600
        self.minutes = leftoversecs // 60
        self.seconds = leftoversecs % 60
    def to_seconds(self):
        # converts to only seconds
        return (self.hours *3600) + (self.minutes *60) + self.seconds
   def increment(self,seconds):
        return MyTime(0,0,self.to_seconds() + seconds)

currentTime = MyTime(2,3,4)
currentTime.increment(10)
print(currentTime) # this gives me the old currentTime even after I increment
print(currentTime.increment(10)) # this gives me the right answer

Upvotes: 0

Views: 47

Answers (2)

Prune
Prune

Reputation: 77837

def increment(self,seconds):
    return MyTime(0,0,self.to_seconds() + seconds)

This makes no attempt to modify the self object passed into the function. You does refer to the object, but in a read-only fashion. You call to_seconds to retrieve the "seconds" version of the object; this result goes into a temporary variable. You then add then seconds parameter to that temporary variable. Finally, you return the sum to the calling program ... which then ignores the returned value.

You need one of two things: either store that result back into currentTime.seconds in the main program, or into self.seconds within the method. In the latter case, don't bother to return the value: it's already stored where needed. I recommend the second case.

Upvotes: 2

JacobIRR
JacobIRR

Reputation: 8946

It seems like you meant to do this:

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

self refers to the instance itself - the one you are currently interacting with.

Upvotes: 1

Related Questions