我在python中創建了一個類,我想創建一個比較方法來比較同一個類的實體。
就像這樣:
class A()。
def __init__(self,a)。
self.var = a
def comparison(self,other)。
if not isinstance(other,self)。 # <<-- ERROR HERE。
raise Exception("You are not comparing apples to apples"/span>)
else:
if self.var==other.var。
print('we are equal')
else:
print('we are different')
這個敵人不會飛。
所使用的意圖將是:
first = A(8)
第二個=A(9)
第三 = A(8)
第四 = ['anything']
first.comparison(second) # 應該給出 "不同"。
first.comparison(third) # 應該給出 "等于"。
first.comparison(fourth) # 應該引發錯誤。
如果用戶傳遞的東西與同一類的另一個實體不同,方法比較應該引發一個例外,如果它們都是同一類的實體,則進行比較。 如何進行呢?
謝謝。
uj5u.com熱心網友回復:
試試這個方法來代替isinstance,isinstance(other, A)對于A的子類也是True。
def comparison(self,other)。
if type(self) is not type(other)。
raise "You are not comparing apples to apples"。
uj5u.com熱心網友回復:
你的實體不是自己,但它是A.
。如果你改變這一行:
if not isinstance(other,self)。
對這個:
if not isinstance(other,A)。
或者對這個:
if not isinstance(other,type(self)>)。
它作業正常。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/310485.html
標籤:
