使用方法不会改变我的对象?

Using a method will not change my object?

我做了一个给时间加秒的方法。例如,如果我有一个小时 15 分钟,并且我使用这个函数并添加了 15,那么新对象应该读取 1 小时 30 分钟。但是,当我在一行中执行 currentTime.increment(10),然后在下一行执行 print(currentTime) 时,打印的是旧的 currentTime,未更新。

我是 类 的新手,所以我不知道它们是否像列表一样更新。如果我定义了一个 list = [2,3,4] 并附加了一个新条目,它将编辑原始列表,这样我就可以 print(list1) 并且它将是带有新条目的旧列表。为什么它在这里不起作用,为什么它只有在我一步完成时才起作用,比如 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

您似乎是想这样做:

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

self 指的是实例本身——您当前正在与之交互的实例。

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

这不会尝试修改传递给函数的 self 对象。您确实 refer 对象,但是以只读方式。您调用 to_seconds 来检索对象的 "seconds" 版本;这个结果进入一个临时变量。然后将 seconds 参数添加到该临时变量。最后,您 return 调用程序的总和...然后忽略 returned 值。

您需要做两件事之一:要么将该结果存储回主程序中的 currentTime.seconds,要么存储到方法中的 self.seconds。在后一种情况下,不必费心 return 值:它已经存储在需要的地方。我推荐第二种情况。