Python:在这种情况下,isinstance()是必需的吗?

2024-09-30 02:25:35 发布

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

我定义了一个类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?在


Tags: 实例方法selfaddreturn定义timedef
3条回答

在python中可以使用重载,但需要额外的代码来处理。您可以在pypi上提供的名为pythonlangutil的包中找到您要查找的内容。在

from pythonlangutil.overload import Overload,signature

@Overload
@signature("int")
def __add__(self,num):
    return Time.intToTime(self,Time.timeToInt(self)+num)

@__add__.overload
@signature("Time")
def __add__(self,other):
    return Time.intToTime(self,Time.timeToInt(self)+Time.timeToInt(other))

您最好使intToTimetimeToInt模块级函数与您的类Time相同级别,并按如下方式实现__add__

def __add__(self, num):
    if isinstance(num, Time):
        num=timeToInt(num)
    elif not isinstance(num, int):
        raise TypeError, 'num should be an integer or Time instance'
    return intToTime(timeToInt(self)+num)

你真的有两个选择:EAFP或LYBL。EAFP(比许可更容易请求原谅)意味着使用try/except:

def __add__(self, other):
   try:
       return Time.intToTime(self, Time.timeToInt(self)+Time.timeToInt(other))
   except AttributeError as e:
       return Time.intToTime(self, Time.timeToInt(self) + other)

请注意,Time.timeToInst(self)有点奇怪;您通常会写self.timeToInt()。在

LYBL的意思是三思而后行,即isinstance。你已经知道了。在

相关问题 更多 >

    热门问题