[Tutor] If not global, how?

antonmuhin at rambler.ru antonmuhin at rambler.ru" <antonmuhin@rambler.ru
Mon Mar 31 12:55:02 2003


Hello vicki,

Monday, March 31, 2003, 8:12:08 PM, you wrote:

vsn> In the app that I am developing, I have some callbacks
vsn> that need data from other methods. I am trying to
vsn> figure out how to make that data available without
vsn> making it global. Here is an example:

vsn> This class is instantiated.

vsn> class EntryClass(Pmw.EntryField):

vsn>         def __init__(self, parent=0):
vsn>                 Pmw.EntryField.__init__(self, parent)

vsn>         def SendCommand(command):
vsn>                 for command in ('\x09','\x06'):
vsn>                         port = serial.Serial(0, 9600, 8, 'N', 2, timeout=2)
vsn>                         port.write(command)
vsn>                         old=outputbox.getvalue()
vsn>                         new=string.join([old, hex(ord(command))])
vsn>                         outputbox.setvalue(new)
vsn>                         input=port.read()
vsn>                         print input
vsn>                         if input:
vsn>                                 returnedval=hex(ord(input))
vsn>                                 if returnedval:
vsn>                                         print returnedval
vsn>                                         old=outputbox.getvalue()
vsn>                                         new=string.join([old, returnedval])
vsn>                                         outputbox.setvalue(new)
vsn>                         port.close()

vsn>         def Callback(self):
vsn>                 value=self.getvalue()
vsn>                 print value
vsn>                 if value
vsn>                         SendCommand(value)

vsn> ------------------------------------
vsn> As you can see, I need to call SendCommand from the
vsn> callback. Since it is not an instance within the class,
vsn> I can't use EntryClass.SendCommand. If I move the call
vsn> to SendCommand into the main code, I don't think I can
vsn> be sure that it was just called and has a value that I
vsn> actually want to send out. I realize that I am probably
vsn> making this much harder than it is, but I am stuck. Can
vsn> someone help me fix this one?

vsn> --vicki




There are several options. One in style of Magnus: use class and
define __call__ method. Another is to use closures (if I use the term
correctly):

def f(x, y):
   return x + y

def bind2nd(f, value2):
   def inner_f(x):
      return f(x, value2)

my_func = bind2nd(f, 1)

my_func(3) # should be the same to f(3, 1)

Warning: I didn't test it.



-- 
Best regards,
 anton                            mailto:antonmuhin@rambler.ru