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()
23  counts[die1.value + die2.value] += 1
24 for i in range(2, ...

Get A Concise Introduction to Programming in Python now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.