Home > Blockchain >  How do I write the __init__ to assign 1 to the __value data attibute for the dice game?
How do I write the __init__ to assign 1 to the __value data attibute for the dice game?

Time:12-03

Write a class named Die that simulates rolling dice. The Die class should have one private data attribute named __value. It should also have the following methods:

  • __init__ : The __init__ method should assign 1 to the __value data attribute.
  • roll: The roll method should set the __value data attribute to a random number from 1 to 6.
  • get_value: The get_value function should return the value of the __value data attribute.

Write a program that creates a Die object then uses a loop to roll the die 5 times. Each time the die is rolled, display its value.

import random(1,6)


class Die:
    


def __init__(self):
        self.number
int(input("Enter a number 1-6":)


def get_value(self):
   for n in number:
        
def main():
    

in   

CodePudding user response:

Hope this help if you mean to create a class to demonstrate rolling dice.

# Write a class named Die with the following methods:
class Die:
    # __init__ method that initializes the die's value to 1
    def __init__(self):
        self.value = 1

    # roll method that generates a random number in the range 1 through 6, and assigns this value to the die's value attribute
    def roll(self):
        import random
        self.value = random.randint(1, 6)

    #  get_value method that returns the die's value
    def get_value(self):
        return self.value

# main function
def main():
    # Create an instance of the Die class, and assign it to a variable named die.
    die = Die()
    # Write a loop that rolls the die 5 times.
    for i in range(5):
        die.roll()
        print(die.get_value())

CodePudding user response:

As you created number variable using self.number,you can create value with self.__value.

Like this: self.__value = randint(1,6).

Be aware that you can create it outside of the __init__ method. But if you do that, the variable will be linked to the class instead of instances (so multiple call to new dice will have the same value).

  • Related