You are on page 1of 2

###################### 20.1 What is a special method attribute? class Colour: def __init(self, red, green, blue): self.

_red = red self._green = green self._blue = blue def __str__(self): return "Colour: R=%d, G=%d, B=%d" % (self._red, self._green, self._blue) ###################### 20.2.1 The __getitem__ special method attribute class lineReader: def __init__(self, filename): # Open the given file for reading, and remember the open fileobject. self.fileobject = open(filename, 'r') def __getitem__(self, index): # Try to read in a line. line = self.fileobject.readline() # If there was no more data to be read if line == "": # close the fileobject. self.fileobject.close() # and raise an IndexError to break out of any enclosing loop. raise IndexError # Otherwise, return the line that was just read. else: return line ###################### 20.3 Sample problem 2 class TypedList: def __init__(self, exampleElement, initialList = []): # The "example element" argument defines the type of element this list # can contain by providing an example of the type of element. self.type = type(exampleElement) if type(initialList) != type([]): raise TypeError("Second argument of TypedList must be a list.") for element in initialList: if type(element) != self.type: raise TypeError("Attempted to add an element of incorrect type t o a typed list.") self.elements = initialList[:] #### class TypedList: def __init__(self, exampleElement, initialList = []): self.type = type(exampleElement) if type(initialList) != type([]): raise TypeError("Second argument of TypedList must be a list.") for element in initialList: self.__check(element) self.elements = initialList[:] def __check(self, element): if type(element) != self.type: raise TypeError("Attempted to add an element of incorrect type to a typed list.") def __setitem__(self, i, element): self.__check(element)

self.elements[i] = element def __getitem__(self, i): return self.elements[i]

You might also like