12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Now, in the context of a GUI, we can register instances of this class as event handlersfor buttons, even though the GUI expects to be able to invoke event handlers assimple functions with no arguments:cb1 = Callback('blue')cb2 = Callback('green')# 'Remember' blueB1 = Button(command=cb1)B2 = Button(command=cb2)# Register handlers# Register handlersWhen the button is later pressed, the instance object is called as a simple function,exactly like in the following calls. Because it retains state as instance attributes,though, it remembers what to do:cb1( )cb2( )# On events: prints 'blue'# Prints 'green'In fact, this is probably the best way to retain state information in the <strong>Python</strong> language—betterthan the techniques discussed earlier for functions (global variables,enclosing-function scope references, and default mutable arguments). With OOP,the state remembered is made explicit with attribute assignments.Before we move on, there are two other ways that <strong>Python</strong> programmers sometimestie information to a callback function like this. One option is to use default argumentsin lambda functions:cb3 = (lambda color='red': 'turn ' + color)print cb3( )# Or: defaultsThe other is to use bound methods of a class—a kind of object that remembers theself instance and the referenced function, such that it may be called as a simplefunction without an instance later:class Callback:def _ _init_ _(self, color):self.color = colordef changeColor(self):print 'turn', self.colorcb1 = Callback('blue')cb2 = Callback('yellow')B1 = Button(command=cb1.changeColor)B2 = Button(command=cb2.changeColor)# Class with state information# A normal named method# Reference, but don't call# Remembers function+selfWhen this button is later pressed, it’s as if the GUI does this, which invokes thechangeColor method to process the object’s state information:object = Callback('blue')cb = object.changeColorcb( )# Registered event handler# On event prints 'blue'This technique is simpler, but less general than overloading calls with _ _call_ _;again, watch for more about bound methods in the next chapter.504 | Chapter 24: Class Coding Details

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!