[英]How to properly overwrite __add__ method and create new object in Python?
[英]Overwrite __add__ method
class Clock:
def __init__(self,hours,minutes):```
self.hours=hours
self.minutes=minutes
def Clock(hours,minutes):
if hours>9 and minutes>9:
return str(hours)+":"+str(minutes)
elif hours>9 and minutes<10:
return str(hours)+":0"+str(minutes)
elif hours<10 and minutes>9:
return "0"+str(hours)+":"+str(minutes)
else:
return "0"+str(hours)+":"+"0"+str(minutes)
def __add__(self,other):
????if Clock.Clock(self.hours,self.minutes)+Clock.Clock(other.hours,other.minutes)????
t=Clock.Clock(5,6)+Clock.Clock(5,6)
print(t)
现在,当我打印t
我得到 05:0605:06,我想知道如何覆盖__add__
函数,当我在做Clock.Clock(self,other)+Clock.Clock(self,other)
它是将打印出Clock(self,other)+Clock(self,other)
这对于上面的输入是 = 10:12。
您正在添加将连接而不是实际添加小时和分钟值的字符串。 你可能想这样做
def __add__(self,other):
return Clock.Clock(self.hours+other.hours,self.minutes+other.minutes)
假设hours和minutes属性是数字
In [4]: class Clock:
...:
...:
...: def __init__(self,hours,minutes):
...: self.hours=hours
...: self.minutes=minutes
...:
...: def __repr__(self):
...: if self.hours>9 and self.minutes>9:
...: return str(self.hours)+":"+str(self.minutes)
...: elif self.hours>9 and self.minutes<10:
...: return str(self.hours)+":0"+str(self.minutes)
...: elif self.hours<10 and self.minutes>9:
...: return "0"+str(self.hours)+":"+str(self.minutes)
...: else:
...: return "0"+str(self.hours)+":"+"0"+str(self.minutes)
...: def __add__(self, other):
...: self.hours += other.hours
...: self.minutes += other.minutes
...: return Clock(self.hours, self.minutes)
In [5]: Clock(5, 6) + Clock(5,6)
Out[5]: 10:12
我对你的代码有一些自由。 首先, Clock
方法看起来像是在尝试转换为字符串。 因此,让我们将其定义为__str__
。 我们还可以更简洁地实现字符串转换。
至于__add__
方法。 为了保持一致,它应该返回一个Clock
对象,而不是一个字符串。
现有答案遗漏的另一件事是考虑总分钟值超过 59 的情况,在这种情况下,超出部分应包含在小时值中。
要计算分钟数,请取总分钟数的模数 ( %
) 60。 小时除以 60 并向下舍入(或仅进行整数除法)。 函数divmod
在一个函数调用中方便地为我们完成了这两件事。
class Clock:
def __init__(self, hours, minutes):
if minutes > 59:
raise ValueError('invalid value for minutes %d' % minutes)
self.hours = hours
self.minutes = minutes
def __str__(self):
return "%d:%02d" % (self.hours, self.minutes)
def __add__(self, other):
extrahours, mins = divmod(self.minutes + other.minutes, 60)
hours = self.hours + other.hours + extrahours
return Clock(hours, mins)
t = Clock(5, 6) + Clock(5, 6)
print(t)
如果我们现在尝试
t = Clock(5, 20) + Clock(5, 50)
它正确打印11:10
而不是10:70
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.