首页 > 解决方案 > 我正在尝试添加时间。我得到 <__main__.MyTime object at 0x039C55C8>。但我期待我的两次添加

问题描述

class MyTime:

    def __init__(self, hrs, mins, sec):
        total_sec = hrs*3600 + mins*60 + sec
        self.hours = total_sec // 3600
        remaining_sec = total_sec % 3600
        self.minute = remaining_sec // 60
        self.sec = remaining_sec % 60

    def to_sec(self):
        return self.hours*3600 + self.minute*60 + self.sec

    def increment(t1, t2):
        secs = t1.to_sec() + t2.to_sec()
        return MyTime(0, 0, secs)
   
t1 = MyTime(9, 14, 30)
t2 = MyTime(3, 35, 0)

print(t1.increment(t2))

标签: pythonpython-3.xclass

解决方案


您正在返回并打印该对象。

如果你想打印秒,那么你应该这样做:

print(t1.increment(t2).to_sec()) # 46170

如果您想要更详细的时间,请将此方法添加到您的课程中:

def __str__(self):
    # or return anything you like, usually descriptive
    return str(self.hours) + ":" + str(self.minute) + ":" + str(self.sec)

并正常打印:

print(t1.increment(t2))

__str__当您尝试打印到对象时将被调用。


推荐阅读