Chapter 23
Writing Classes
No programming language can anticipate all data types that a programmer
might eventually need, and so object-oriented languages allow you to create
new data types by defining classes. We start with a simple example to highlight
the new concepts.
Listing 23.1: Sum of Dice
1 # dicesum.py
2
3 from random import randint
4
5 class Die:
6 def __init__(self):
7 self.roll()
8
9 def roll(self):
10 self.value = randint(1, 6)
11
12 def __str__(self):
13 return str(self.value)
14
15 def main():
16 rolls = int(input("Enter the number of times to roll: "))
17 die1 = Die()
18 die2 = Die()
19 counts = [0]
*
13
20 for i in range(rolls):
21 die1.roll()
22 die2.roll() ...
Get A Concise Introduction to Programming in Python now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.