python exec, add staticmethod to class -
in python can do:
exec(code_string, globals(), some_object.__dict__) to add method object. possible add static method class in sort of similar fashion? like:
exec(code_string, globals(), classname.__dict__) so statically call method:
classname.some_static_method() what i'm trying add new staticmethods during runtime given python code defining method. i.e. if given:
code_string = ''' @staticmethod def test(): return 'blah' ''' how can create , instantiate class call it?
hopefully clear enough, thank you!
edit: working example of adding function object:
class testobject(object): pass code_string = ''' def test(): return 'blah' ''' t = testobject() exec(code_string, globals(), t.__dict__)
use setattr()
>>> code_string = ''' ... @staticmethod ... def test(): ... return 'returning blah' ... ''' >>> >>> exec(code_string) >>> test <staticmethod object @ 0x10fd25c58> >>> class classname(object): ... def instancemethod(self): ... print "instancemethod!" ... >>> setattr(classname, 'teststaticmethod', test) >>> classname.teststaticmethod() 'returning blah' >>>
Comments
Post a Comment