2013-12-23 27 views
0

我想爲練習製作一個概率類的類,所以我構建了一個類P,並希望能夠與它關聯。我也希望能夠添加像P(「a」)+ P(「b」)這樣的概率並讓它增加它們的值。這對代碼來說很好,但是我在測試時遇到了一些奇怪的行爲。我只粘貼下面的代碼的相關部分[這就是爲什麼它似乎有點冗長]:在類中__add__意外的Python行爲

class P: 

def __init__(self, event): 
    self.event = event 
    self.v = 0 

def value(self, val): 
     """Sets the probability to the value 'val'.""" 
    self.v = val 

def add_stuff(x,y): 
    return lambda x,y: x+y 

def __add__(self, other): 

    if isinstance(other, P): # if we are adding two P's together. 
     return add_stuff(self.v, other.v) 

    else:      # if we are adding a number to our P. 
     try: return add_stuff(self.v, other) 
     except: raise TypeError(self.type_error_string) 



a = P("a") # Creates the instances. 
b = P("b") # 
c = P("c") # 

a.value(0.5) # Sets the value of a.v to 0.5, 
b.value(0.1) # and so on for b and c. 
c.value(0.2) # 

print a.v + b.v == 0.7. # prints True. 
print b.v == 0.1  # prints True. 
print c.v == 0.2  # prints True. 
print b.v + c.v   # prints 0.3. 
print type(b.v + c.v) # prints <float> 
print b.v + c.v == 0.3 # prints False (!!). 

這裏的相關部分是底部。請注意,a.v + b.v [以及其他一些值]在測試時很好,但出於某種原因,不會出現b.v + c.v。我不確定這裏發生了什麼。

+2

這有什麼好做OOP,無關的'__add__'過載,什麼都做用浮點算法。 –

+1

'.2 + .1 == .3'總是錯誤的,幾乎所有語言都使用浮點數 – tobyodavies

+0

Dang。真?我不知道。我會刪除這個問題。有什麼辦法可以解決這個問題嗎? – james

回答

0

根據您的add_stuff__add__定義,它看起來像你需要有這樣的:

def __add__(self,other): 
    ... 
    return add_stuff(self.v, other.v)(self.v,other.v) # add_stuff() returns a function which gets used in the second set of brackets 
    ...