Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equality operator override problem

Tags:

python

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.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

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?

like image 965
David Weng Avatar asked Dec 06 '22 21:12

David Weng


2 Answers

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
like image 92
Cédric Julien Avatar answered Dec 28 '22 23:12

Cédric Julien


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'
like image 24
Ondrej Slinták Avatar answered Dec 28 '22 23:12

Ondrej Slinták