2017-09-26 96 views
1

我在使用更廣泛的python腳本中的運算符方法時遇到問題。爲了縮小這個問題,我創建了下面的示例代碼。嘗試在Python中使用運算符方法時出現類型錯誤

class Car: 
    def __init__(self, Name, Speed): 
     self.Name = Name 
     self.Speed = Speed 
     self.PrintText() 

    def PrintText(self): 
     print("My %s runs %s km/h." % (self.Name, self.Speed)) 

    def GetName(self): 
     return self.Name 

    def GetSpeed(self): 
     return self.Speed 

    def __sub__(self, other): 
     try: # Try with assumption that we have to deal with an instance of AnotherClass 
     a = self.GetSpeed() 
     except: # If it doesn't work let's assume we have to deal with a float 
     a = self 

     try: # Try with assumption that we have to deal with an instance of AnotherClass 
     b = other.GetSpeed() 
     except: # If it doesn't work let's assume we have to deal with a float 
     b = other 

     return a - b 

Car1 = Car("VW", 200.0) 
Car2 = Car("Trabant", 120.0) 
print("") 

Difference = Car1 - Car2 
print("The speed difference is %g km/h." % Difference) 
print("") 

Difference = Car2 - 6.0 
print("My %s is %g km/h faster than a pedestrian." % (Car2.GetName(), Difference)) 
print("") 

Difference = 250.0 - Car1 
print("I wish I had a car that is %g km/h faster than the %s." % (Difference, Car1.GetName())) 

輸出爲:

My VW runs 200.0 km/h. 
My Trabant runs 120.0 km/h. 

The speed difference is 80 km/h. 

My Trabant is 114 km/h faster than a pedestrian. 

Traceback (most recent call last): 
    File "test.py", line 41, in <module> 
    Difference = 250.0 - Car1 
TypeError: unsupported operand type(s) for -: 'float' and 'instance' 

我怎麼能解決時出現的第一個對象是一個浮動的問題?

+0

你需要'__rsub__' –

+0

下面的答案是正確的。我只是想提供建議。您可以使用'__str__'方法代替PrintText函數。然後你可以像這樣輸入:'print(Car)' – Nuchimik

回答

1

您需要定義與反向操作數減法(本身是固定//你的問題的代碼,但可能需要更多的清洗):

def __rsub__(self, other): 
     a = self.GetSpeed() 

     try: # Try with assumption that we have to deal with an instance of AnotherClass 
     b = other.GetSpeed() 
     except AttributeError: # If it doesn't work let's assume we have to deal with a float 
     b = other 

     return b - a 

現在你的輸出:

My VW runs 200.0 km/h. 
My Trabant runs 120.0 km/h. 

The speed difference is 80 km/h. 

My Trabant is 114 km/h faster than a pedestrian. 

I wish I had a car that is 50 km/h faster than the VW. 
1

不是真的你的具體問題的答案,但它會減少實際速度速度,而不是汽車速度。 只要做car1.Speed() - car2.Speed()car2.Speed() - 6.0。否則,你創建自己的問題。

作爲一個方面說明我也建議你遵循Python的風格指南https://www.python.org/dev/peps/pep-0008/

相關問題