Dynamically add methods to python classes)
Someone in the group asked how to copy the code def foo (): pass class Bar (object): pass Bar. set_instance_method (foo) B = Bar () B. foo () Copying code is actually relatively simple. You only need to write a function to set attributes for the class. You can determine whether to use function packaging as required, or use the staticmethod decorator: copy the code import functools def foo (): print 'Hello world' class Bar (object): def _ init _ (self): self. data = 42 @ classmethod def set_instance_method (cls, func): @ functools. wraps (func) def dummy (self, * args, ** kwargs): func (* args, ** kwargs) setattr (cls, func. func_name, dummy) Bar. set_instance_method (foo) B = Bar () B. foo () print B. fooprint Bar. foo copies the code output hello world <bound method Bar. foo of <__ main __. bar object at 0x10d41c890 >>< unbound method Bar. foo> then I asked how to write this: def foo (): pass class Bar (object): set_instance_method (foo) the problem is how to obtain the Bar when set_instance_method is running. However, if you try it, you can only get the Bar (through the inspect module ). I am not very familiar with the Internal principles of python. I only know that Bar does not exist when Bar is defined, so I cannot do this.