0

I have written a class to simulate the throw of a dice. I am trying to implement the private method __check_dice(self) to catch errors when creating an instance of the class to avoid code duplication:

import numpy as np


class Dice():


    """ Simulating the roll of a dice with possible outcomes ranging
    from first_num to last_num (inclusive) """

        def __init__(self, first_num=1, last_num=6):
        self.first_num = first_num
        self.last_num = last_num

    def __check_dice(self):
        if self.last_num >= self.first_num >= 0:
            return True
        else:
            return "The first number should be smaller than the last.." \
                "and both positive. I can't create your dice.."

    def sides(self):
        if __check_dice(self):
            return "Our dice has {} sides". \
                format(self.last_num + 1 - self.first_num)

    def roll(self):
        if __check_dice(self):
            return "You rolled a " + \
                str(np.random.choice(np.arange(self.first_num,
                                           self.last_num + 1)))


dice_1 = Dice(-1, 18)
print(dice_1.sides())
print(dice_1.roll())

The logic is that when the __check_dice evaluates to True, the two following methods can be executed if called. However when running the code I get the following error:

    if __check_dice(self):
NameError: name '_Dice__check_dice' is not defined

Why is it not possible to call the __check_dice method within the scope of the class inside another method? I have also tried without making the method private, but I get similar error.

gxpr
  • 836
  • 9
  • 12
  • [Related](https://stackoverflow.com/questions/70528/why-are-pythons-private-methods-not-actually-private). – user202729 Mar 27 '18 at 10:28
  • 1
    Because `__check_dice` is a class method and needs to be called through its class object (`self` in this case). Change `__check_dice(self)` to `self.__check_dice()`. – Mazdak Mar 27 '18 at 10:37
  • Possible duplicate of [Python call function within class](https://stackoverflow.com/questions/5615648/python-call-function-within-class) – user202729 Mar 27 '18 at 10:38
  • I have tried without a private method and also tried self.__check_dice(). Neither seem to catch the error though.. – gxpr Mar 27 '18 at 10:42

1 Answers1

1

The work around was to change the __check_dice(self) to:

def __check_dice(self):
    if self.last_num >= self.first_num >= 0:
        return True
    else:
        return False

Then following Kasramvd comment and doing the changes, the code worked as expected.

gxpr
  • 836
  • 9
  • 12