我定义了一个类Time
,它有三个int属性:hrs, min, sec
我定义了方法intToTime()
,它将一个Time
实例转换为int
,这是一段时间内的秒数,也是一个方法timeToInt()
,做相反的操作。在
我希望他们实现__add__
,这样我就可以做一些事情,比如“TimeA+TimeB”或“TimeA+100”,其中100是添加到TimeA的秒数。在
因为我想合并这两个(因为Python中没有重载)
def __add__(self,num):
return Time.intToTime(self,Time.timeToInt(self)+num)
def __add__(self,other):
return Time.intToTime(self,Time.timeToInt(self)+Time.timeToInt(other))
“num”应该是一个int,“other”是另一个时间实例。我知道一种使用isinstance()的方法。在
但我的问题是, 在这种情况下,如何在不使用isinstance()的情况下实现这样一个add?在
在python中可以使用重载,但需要额外的代码来处理。您可以在pypi上提供的名为pythonlangutil的包中找到您要查找的内容。在
您最好使
intToTime
和timeToInt
模块级函数与您的类Time
相同级别,并按如下方式实现__add__
:你真的有两个选择:EAFP或LYBL。EAFP(比许可更容易请求原谅)意味着使用try/except:
请注意,
Time.timeToInst(self)
有点奇怪;您通常会写self.timeToInt()
。在LYBL的意思是三思而后行,即isinstance。你已经知道了。在
相关问题 更多 >
编程相关推荐