平等操作员覆盖问题

Dav*_*eng 4 python

我是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
Run Code Online (Sandbox Code Playgroud)

当我做

if(goal1 == goal2):
    print "match"
Run Code Online (Sandbox Code Playgroud)

它引发了这个错误

File "/home/dave/Desktop/goal.py", line 24, in __eq__
    return self.name == other.name
AttributeError: 'str' object has no attribute 'name'
Run Code Online (Sandbox Code Playgroud)

我在这做错了什么?

Céd*_*ien 7

回溯似乎表明你的goal2是一个字符串对象,而不是一个Goal对象,但你可以这样做来保护自己:

def __eq__(self, other):
    try:
        return self.name == other.name
    except AttributeError:
        return False
Run Code Online (Sandbox Code Playgroud)


Ond*_*ták 6

它在Python 2.6中对我来说就像一个魅力.变量之一很可能不是Goal对象.正确使用应该是:

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

if (a == b):
    print 'yay'
else:
    print 'nay'
Run Code Online (Sandbox Code Playgroud)