我是python的新手,这是我的课程
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'
我在这做错了什么?
回溯似乎表明你的goal2是一个字符串对象,而不是一个Goal对象,但你可以这样做来保护自己:
def __eq__(self, other):
    try:
        return self.name == other.name
    except AttributeError:
        return False
它在Python 2.6中对我来说就像一个魅力.变量之一很可能不是Goal对象.正确使用应该是:
a = Goal('a', 1);
b = Goal('b', 2);
if (a == b):
    print 'yay'
else:
    print 'nay'
| 归档时间: | 
 | 
| 查看次数: | 3511 次 | 
| 最近记录: |