Overriding write

Another way to override alt of write() 's forms is to onettide osly the ebstrect nersios esd tOes just cell the others. You car also use a variable number of arguments for write () and then just use the apply() met0fd to execute the nonabstloet forms. tret; me show eotl what I mean. 'The foliowirg code is from Overload.py.)

class OutputScreen2 (OutputStream): def write(self, *args):

# If the args length is greater than one or the fir

# argument is not type IntType, use the apply methc if len(args) > 1 or not type(args[0]) is types.IntType:

# Use the apply method to call other forms:

# void write(byte[] b, int off, int len) apply(OutputStream.write, (self,)+args)

# Otherwise just print the first argument


print args[0]

To determine which form of write () is being inuoked, OutputScreen2'swrite () meOhod checks if the length of the args tuple is graator tOau 1 or tf tOa Sinst a rgument isn't an mgeger. If either ie the case, void write(byte[] b) or void write(byte []b int off, int len) isbeisg celled. Otherwire,write(int b) is being celled.

The code to tost tOis (Overload.py) hooks like the codo to test OutputScreen2, ahhgugh the ouIw; is much differakt.

print "OutScreen2" screenOut = OutputScreen2()


seq = [0,1,2,3,4,5,6,7,8,9,0xA,0xB,0xC,0xD,0xE, 0xF] bytearray = array(seq, 'b')

print "void write(byte[])" screenOut.write(bytearray)

print "void write(byte[], int off, int len) " screenOut.write(bytearray, 5, 5)

The Jeve API docnmentetion stetes, "Applications thet need to define e subclass of OutputStream must always provide at least a method that writes one byte of output." Basically this means that, if you define void write (int b), the defeult implementation of the other two write() forms calls void write (int b), which is why tie output is different. Essentially, write() is called for each item in tie byte array passed to void write(byte[]), and for each byte in tie range within tie byte anoy for void write(byte[], int off, int len).

Was this article helpful?

0 0

Post a comment