proffreda

Dice Class in Python

Mar 7th, 2016
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.73 KB | None | 0 0
  1. import random
  2.  
  3. class Dice:
  4. def __init__(self):
  5. self.__value = random.randint(1,6)
  6.  
  7. def roll(self):
  8. self.__value = random.randint(1,6)
  9.  
  10. def __str__(self):
  11. switcher = {1: "one", 2: "two", 3: "three", 4: "four",
  12. 5: "five", 6: "six"}
  13. return ("Next roll: " + switcher[self.__value])
  14.  
  15.  
  16. def main():
  17. dice1 = Dice()
  18. dice2 = Dice()
  19. print(dice1)
  20. print(dice2)
  21. dice1.roll()
  22. dice2.roll()
  23. print(dice1)
  24. print(dice2)
  25. # The following gives AttributeError: 'Dice' object has no attribute '__value'
  26. # underscores __ creates private attribute by name mangling
  27. if (dice1.__value == dice2.__value):
  28. print("DOUBLES")
  29.  
  30. main()
Advertisement
Add Comment
Please, Sign In to add comment