2014-02-25 57 views
5

我定义的类Time有三个INT属性:hrs, min, secPython:Isinstance()在这种情况下是必需的吗?

我定义了一个Time实例转换为int,这是秒,在这段时间的数量,也是一个方法timeToInt()那些方法intToTime()相反。

我希望他们实现__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)) 

“民”应该是一个int,“其他”是另一个时间点。我知道使用isinstance()的一种方法。

但我的问题是, 在这种情况下,我应该如何实现这样一个而不使用isinstance()?

+0

但是你现在没有使用isintance。 – Eenvincible

+1

后者'__add__'会影响前者,因为python中没有方法重载。 –

+0

在这里,一个时间实例只是三个整数的组合:hrs,min和sec –

回答

7

你真的有两种选择:EAFP或LYBL。 EAFP(更容易请求原谅比许可)是指使用的try /除外:

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意味着在你跳跃之前 - 即是实例。你已经知道一个。

+1

这是恕我直言,太大了。如果'AttributeError'发生在其他地方呢?我会'尝试:add = Time.timeToInt(other)\ n,除了AttributeError as e:add = other',然后使用'add'添加它:'return Time.intToTime(self,Time.timeToInt(self) +添加)' – glglgl

1

你最好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) 
0

有可能在Python中使用过载,但它需要额外的代码来处理它。你可以在名为pythonlangutil的软件包中找到你正在寻找的东西,它可以在pypi上找到。

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))