O'Reilly logo

A Concise Introduction to Programming in Python by Mark J. Johnson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required