ellriley
ellriley

Reputation: 655

Why am I getting this attribute error in Python?

Thanks in advance for any help, I know this is probably a newb question but I just can't find anything via search that seems to answer my question. This is the relevant part of the traceback:

  File "war.py", line 183, in __battle
    if (card1 > card2):
  File "war.py", line 24, in __lt__
    return self.int_id % 13 < other.int_id % 13
AttributeError: 'function' object has no attribute 'int_id'

I'm confused about what this means....what is the 'function' object? Also, why is calling lt from a line that's doing a greater than comparison? Why is this a problem now, given that I unit tested my Card class (of which card1 and card2 are instances of), including all rich comparison operators, and it passed?

These are the definition of the rich comparison methods in my Card class (int_id is, as you would probably guess, just an instance variable int):

(sorry the indenting below got messed up)

class Card():

    def __init__(self, int_id):
        self.int_id = int_id

    def __lt__(self, other):
        return self.int_id % 13 < other.int_id % 13

    def __le__(self, other):
        return self.int_id % 13 <= other.int_id % 13

    def __eq__(self, other):
        return self.int_id % 13 == other.int_id % 13

    def __ne__(self, other):
        return self.int_id % 13 != other.int_id % 13

    def __gt__(self, other):
        return self.int_id % 13 > other.int_id % 13

    def __ge__(self, other):
        return self.int_id % 13 >= other.int_id % 13

Upvotes: 0

Views: 250

Answers (2)

Kevin
Kevin

Reputation: 76184

From the error 'function' object has no attribute 'int_id', I would guess that a function object is being compared against a Card in the line if (card1 > card2):. This might occur if one of the cards was mistakenly assigned as a function. For example, card1 = getMyOtherCard instead of card1 = getMyOtherCard().

Upvotes: 5

ecatmur
ecatmur

Reputation: 157314

card1 has somehow come to refer to a function (have you left out parentheses on a function or method call?).

As a result, card1 < card2 gets rearranged to card2 < card1 (because function objects don't have comparison operators), which is why __lt__ is being called.

From http://docs.python.org/reference/datamodel.html#object.__lt__:

There are no swapped-argument versions of these methods (to be used when the left argument does not support the operation but the right argument does); rather, __lt__() and __gt__() are each other’s reflection [...]

Upvotes: 2

Related Questions