Search code examples
pythonclasstypeerror

Python - TypeError: 'int' object is not callable


(Using Python 2.7)

Hello,

I've two version of a class PairOfDice.

1.) This one is not working and throws an error.

TypeError: 'int' object is not callable

import random

class PairOfDice:
    """ Represent the Pair of Dices and have method which tells the total of those roles.
    """
    def roll(self):
        self.total = random.randint(1, 6) + random.randint(1, 6)

    def total(self):
        return self.total

    def name(self, name):
        self.name = name

    def getName(self):
        return self.name

player1 = PairOfDice()
player1.roll()
print player1.total()

2) This one is working.

import random

class PairOfDice:
    """ Represent the Pair of Dices and have method which tells the  total of those roles.
    """
    def roll(self):
        self.roll1 = random.randint(1, 6)
        self.roll2 = random.randint(1, 6)

    def total(self):
        return self.roll1 + self.roll2

    def name(self, name):
        self.name = name

    def getName(self):
        return self.name

player1 = PairOfDice()
player1.roll()
print player1.total()

Can please someone explain what's wrong with the first one?

Thanks


Solution

  • In the first class total is a function as well as an attribute of the class. That is not okay :) Python thinks that the total you are referring to in the final line is the integer variable total and not the function.

    It is considered a good practice to name the function total as get_total instead