开发者

Equality operator override problem

开发者 https://www.devze.com 2023-03-02 09:43 出处:网络
I\'m new to python, this is a class that I have class Goal: def __init__(self, name, value): self.name = name

I'm new to python, this is a class that I have

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.valu开发者_如何学JAVAe < 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

When I do

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

it raises this error

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

What am I doing wrong here?


The traceback seems to indicate that your goal2 is a string object, not a Goal object but you can do this to protect yourself :

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


It works like a charm for me in Python 2.6. There's high probability that one of variables isn't Goal object. Proper usage should be:

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

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


You can further protect your equality operator:

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

精彩评论

暂无评论...
验证码 换一张
取 消