Python Standard Library--functools module

Source: Internet
Author: User

Functools module: Tools for managing functions

Partial object: wrapping the original function, providing a default value
Import functools# original function def myfunc (a, b=2):    """docstring for MyFunc ()."""Print ('called MyFunc with:', a, b)return# output function def show_details (name, f, is_partial=False): print (name) print (f)ifnot Is_partial:print (f.__name__)ifis_partial:print (f.func) Print (f.args) print (f.keywords)return# show_details ('MyFunc', Myfunc) # myfunc ('a',3) P1= Functools.Partial(myfunc, b=4) # The function show_details after wrapping ('partial with named', p1, True) p1 ('Passing a'# Call the wrapper after the function P1 ('Override B', b=5)

Copy the properties of the original function to the partial object

Functools.update_wrapper (p1, Myfunc)      # comment out this line, run error print (p1.__name__) print (p1.__doc__)

Wrapping a function of an instance object

classMyClass (Object): def method (self, a, B=2):        """docstring for method ()."""Print ('called method With:', a, b)returno=MyClass () p1= Functools.Partial(o.method, b=4) Show_details ('partial with named', p1, True) functools.update_wrapper (p1, o.method) print (p1.__name__) print (p1.__doc__)

@functools. Wraps Decorators

def simple_decorator (f):    @functools. wraps (f)    def decorated (a='decorated' , b=1):        print (a, b)        f (a,b =b)        return    return = simple_decorator (myfunc) print (wrapped.__name__) print (wrapped.__doc__) 
@functools. total_ordering

To add a rich comparison method to a class, the class must provide __eq__ and another rich comparison method

@functools. Cmp_to_key (cmp_obj)

Python Standard Library--functools module

Related Article

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.