2

(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

courage
  • 806
  • 1
  • 8
  • 9
  • 1
    Assigning a value to `self.total` overrides the `self.total` method; you're calling that number in the last line of the first example. A class instance only has one namespace, including both values and methods. – jasonharper Jul 15 '17 at 17:54
  • Although the error message for the first duplicate does not match, the underlying cause is the same, as is the remedy. – Karl Knechtel Sep 08 '22 at 03:23

2 Answers2

3

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

Banach Tarski
  • 1,821
  • 17
  • 36
3

This is because you have a property called total, as well as a function called total. When you run roll, you are overwriting the class's definition of total.

In other words, before you run roll, player1.total is a function. However, once you run roll, you set player1.total to be a number. From then on, when you reference player1.total, you are referring to that number.

You might want to rename the total function to something like getTotal, or something similar.

ollien
  • 4,418
  • 9
  • 35
  • 58