python - 我正在尝试添加时间。我得到 <__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))
解决方案
您正在返回并打印该对象。
如果你想打印秒,那么你应该这样做:
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__
当您尝试打印到对象时将被调用。
推荐阅读
- java - 对 JRXML 中超过 1000 列的 Oracle 错误使用 IN 子句
- macos - 如何在终端中批量重命名文件?
- python - 如何找到 3 通道图像的均值和标准差
- reactjs - 在 reactjs 中将值保存在表单中
- reactjs - React - 材质 UI 与 Reactstrap
- java - 如何将文本文件中的不同数据类型添加到数组列表中?
- qt - 如何提高图形质量
- apache-spark - 如何使用 Hive 仓库连接器在 pyspark 中执行 HQL 文件
- python - Django 精神在创建主题时生成无法在 settings.CACHES 中找到“%s”的配置错误”
- asp.net-core - OnGet 中的异步不会等待函数结束,而是会转到剃刀文件?