Case Study: PPM Image Class
Now that you have seen and written a few classes, it may b e helpful to see
the complete code for the ImagePPM class used in Chapters 21 and 22.
Listing 24.3: ImagePPM
1 # image.py
2
3 def clamp(x, a, b):
4 return max(a, min(b, x))
5
6 class ImagePPM:
7 @classmethod
8 def new(cls, size):
9 newimg = ImagePPM()
10 newimg.size = size
11 newimg.maxval = 255
12 newimg.data = [0]
*
3
*
size[0]
*
size[1]
13 return newimg
14
15 @classmethod
16 def open(cls, fname):
17 newimg = ImagePPM()
18 with open(fname) as f:
19 header = f.readline()
20 if not header.startswith("P3"):
21 return None
22 nextline = f.readline()
23 while nextline.startswith("#"):
24 nextline ...
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.