2013-12-23 25 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 
    ...