Dynamically add methods to python classes)

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.