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

时间:2018-07-17 23:05:20

标签: python python-3.x class object computer-science

我制作了一种将时间增加几秒的方法。例如,如果我有一个小时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

2 个答案:

答案 0 :(得分:2)

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

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

您需要执行以下两项操作之一:将结果存储回主程序中的currentTime.seconds或方法中的self.seconds中。在后一种情况下,不必费心返回该值:它已经存储在需要的位置。我推荐第二种情况。

答案 1 :(得分:1)

您似乎打算这样做:

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

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