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

2024-05-29 10:05:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我做了一个在时间上加秒的方法。例如,如果我有1小时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

Tags: toself列表timedefsecondsprint小时
2条回答
def increment(self,seconds):
    return MyTime(0,0,self.to_seconds() + seconds)

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

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

看来你是有意这么做的:

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

self引用实例本身—您当前正在与之交互的实例

相关问题 更多 >

    热门问题