2011-04-30 38 views
4

我是新来的蟒蛇,这是一类,我有平等操作符重载问题

class Goal: 
    def __init__(self, name, value): 
     self.name = name 
     self.value = value 

    def is_fulfilled(self): 
     return self.value == 0 

    def fulfill(self, value): 
     if(self.value < value): 
      value = self.value 

     self.value -= value 

    def debug(self): 
     print "-----" 
     print "#DEBUG# Goal Name: {0}".format(self.name) 
     print "#DEBUG# Goal Value: {0}".format(self.value) 
     print "-----" 

    def __eq__(self, other): 
     return self.name == other.name 

当我做

if(goal1 == goal2): 
    print "match" 

它提出了这个错误

File "/home/dave/Desktop/goal.py", line 24, in __eq__ 
    return self.name == other.name 
AttributeError: 'str' object has no attribute 'name' 

什么我在这里做错了吗?

回答

6

它的工作原理就像在Python 2.6我的魅力。其中一个变量不是Goal对象的概率很高。正确用法应该是:

a = Goal('a', 1); 
b = Goal('b', 2); 

if (a == b): 
    print 'yay' 
else: 
    print 'nay' 
7

回溯似乎表明,你的目标2是一个字符串对象,而不是目标对象 ,但你可以做到这一点,以保护自己:

def __eq__(self, other): 
    try: 
     return self.name == other.name 
    except AttributeError: 
     return False 
+0

一个更好的办法是使用,而不是一个try-catch isinstance。 – 2015-07-16 20:48:27

2

可以进一步保护您的平等运营商:

def __eq__(self, other): 
    if type(self) != type(other): 
     raise ValueError('comparing apples and carrots (%s)'%type(other)) 
    return self.name == other.name