Write a class named
Diethat simulates rolling dice. TheDieclass should have one private data attribute named__value. It should also have the following methods:
__init__: The__init__method should assign 1 to the__valuedata attribute.roll: The roll method should set the__valuedata attribute to a random number from 1 to 6.get_value: Theget_valuefunction should return the value of the__valuedata attribute.Write a program that creates a
Dieobject 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).
