Monday, August 8, 2011

How to attach a function to a class

In "Presenting stimulus for fixed duration" we saw how we can easily write a new class to extend existing classes with new functions. While it works, I always had the problem to put this class on every computer and to have it work correctly with different Python Path settings. So, here is a neat trick how to do the same without writing your own class:


from pyepl.locals import *
def present_fixed_dur(clk=None, duration=None, bc=None, minDuration=None):
"""
This is just like the standard Image.present, except
that if you press a button, the image stays on the
screen until the full duration has passed.

I got rid of the jitter argument, because it makes
things complicated.
"""

v = VideoTrack.lastInstance()

# get the clock if needed
if clk is None: clk = PresentationClock()

# show the image
t = v.showCentered(self)
timestamp = v.updateScreen(clk)

if bc:
# wait for button press
button,bc_time = bc.waitWithTime(minDuration,duration,clk)
# figure out how much time is remaining, now
# that they've pressed the button, and delay for
# just that
rt = bc_time[0] - timestamp[0]
clk.delay(duration-rt)
else:
clk.delay(duration)

# unshow that image
v.unshow(t)
upd_ts = v.updateScreen(clk)
# print 'presented for %ims' % (upd_ts[0] - timestamp[0])

if bc: return timestamp,button,bc_time
else: return timestamp

# Use a reference to the function and attach it as a attribute to the Image class
Image.present_fixed_dur = present_fixed_dur


Et voila, we extended the Image class on the fly. :)


No comments: