2014-02-25 59 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))