Hi, group, I am trying to dynamically add a method to class by following this post:
http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/2ec2ad7a0a5d54a1/928e91be352c6bfc?q=%22new.code(%22+%22import+new&_done=%2Fgroup%2Fcomp.lang.python%2Fsearch%3Fgroup%3Dcomp.lang.python%26q%3D%22new.code(%22+%22import+new%26qt_g%3D1%26&_doneTitle=Back+to+Search&&d#928e91be352c6bfc But I got the Error like the below: *******Error********************** Traceback (most recent call last): File "C:\Documents and Settings\cwu\Desktop\t1.py", line 36, in ? C().f2(1,2,4,x='x') File "C:\Documents and Settings\cwu\Desktop\t1.py", line 19, in newf2 self.f() SystemError: C:\sf\python\dist\src-maint23\Objects\cellobject.c:22: bad argument to internal function *******Error********************** Anybody has a thought about this problem? My sample code is pasted as the below: *********Code******************************* ##import new ##import sys ## ##def safe_tuple(seq): ## """Force func_code attributes to tuples of strings. ## ## ## Many of the func_code attributes must take tuples, not lists, ## and *cannot* accept unicode items--they must be coerced to strings ## or the interpreter will crash. ## """ ## seq = map(str, seq) ## return tuple(seq) ## ##class C: ## def __init__(self): ## def _generic(*a,**k): ## print vars() ## self.f() ## ## def _newmethod(newname): ## fcode = _generic.func_code ## #code( argcount, nlocals, stacksize, flags, codestring, constants, names, varnames, filename, name, firstlineno, lnotab) ## fcode_new = new.code(fcode.co_argcount, fcode.co_nlocals, fcode.co_stacksize, ## fcode.co_flags, fcode.co_code, tuple(fcode.co_consts), # Notice co_consts should *not* be safe_tupled. ## safe_tuple(fcode.co_names), safe_tuple(fcode.co_varnames), ## fcode.co_filename, ## newname, ## fcode.co_firstlineno, fcode.co_lnotab) ## return new.function(fcode_new,globals()) ## setattr(self,'f2',_newmethod('newf2')) ## ## def f(): ## print 'from f' ## ##C().f2(1,2,4,x='x') ## ## **********Code************************ *Sorry, I have to put comment chars before the code to preserve the proper indentation. Thanks a lot! CW -- http://mail.python.org/mailman/listinfo/python-list