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?
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'
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With