等号重载问题

4 投票
3 回答
3556 浏览
提问于 2025-04-16 16:42

我刚开始学习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'

我这里做错了什么呢?

3 个回答

2

你可以进一步保护你的相等运算符:

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

错误信息显示你的 goal2 是一个字符串对象,而不是一个 Goal 对象。不过你可以这样做来保护自己:

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

在我使用Python 2.6的时候,这个方法效果很好。很有可能你用的某个变量不是Goal对象。正确的用法应该是:

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

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

撰写回答