can i define a new method at runtime?

Hung Jung Lu hungjunglu at yahoo.com
Sun Jun 20 11:49:07 EDT 2004


raoulsam at yahoo.com (Raoul) wrote:
> 
> but i have literally hundreds of these things to do....
> 
> I'd like to be able to say somethign like
> 
> myTextBox.change = lambda x : verifyInteger(x)
> 
> so when i initialize my form i'd like to run through a list that looks
> like
> 
> [["controlName1","verifyInteger"],["controlName2,"verifyFloat"],["controlName3
> "verifyInteger"]

def change_Integer(self):
    try:
        string.atoi(self.value)
    except ValueError:
        message(...)
        self.setFocous()
def change_Currrency(self):
    ...

dict = {"box1": "Integer", "box2": "Currency"}

import new
for (box_name, box_type) in dict.iteritems():
    function_name = 'change_%s' % box_type
    f = eval(function_name)
    box = getattr(myFrame, box_name)
    box.change = new.instancemethod(f, box, box.__class__)

replace eval() by globals() if safety is a concern, or replace by
getattr(...) if functions are defined in modules or classes. (.im_func
maybe needed, anyway, you'll figure out the specifics on your own.)

Hung Jung



More information about the Python-list mailing list