[Tutor] click and line

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Mon Nov 7 04:21:22 CET 2005


Hi Shi Mu,

Let's look at click():

##########################
def click(event):
    print event.x, event.y
    m1=event.x
    n1=event.y
##########################

By default, variable names in functions are local.  Do you know about
local vs global variables?  The assignments to m1 and n1 won't be
remembered once we come out of the click() function.


It sounds like you want a function-like thing that remembers the very last
event we passed to it before.  One way to do this is to use globals,
because globals last beyond function calls.

For example:

######
>>> n = None
>>> def lastNumber(x):
...     global n
...     print "I last saw", n
...     n = x
...
>>> lastNumber(42)
I last saw None
>>> lastNumber(17)
I last saw 42
>>> lastNumber(3)
I last saw 17
######

So for something very simple, using a global will probably be easiest.


However, there are other approaches that don't use globals. One that fits
Python's model well is to use a class instance, since instances can store
state:

######
>>> class LastNumber:
...     def __init__(self):
...         self.n = None
...     def getAndSet(self, x):
...         value = self.n
...         self.n = x
...         return value
...
>>> last = LastNumber()
>>> last.getAndSet(42)
>>> last.getAndSet(3)
42
>>> last.getAndSet(7)
3
>>> last.getAndSet(9)
7
######


Does this make sense?  Please feel free to ask questions here.



More information about the Tutor mailing list