Smooth python and cookbook learning notes (9), pythoncookbook

Source: Internet
Author: User

Smooth python and cookbook learning notes (9), pythoncookbook
1. Reduce the number of parameters of callable objects and use functools. partial to freeze Parameters

Use functools. partial () to fix one or more values to reduce the call parameters.

>>> Def spam (a, B, c, d ):... print (a, B, c, d)...> from functools import partial >>> s1 = partial (spam, 1) # set the value of a to 1 >>> s1 (2, 3, 4) 1 2 3 4> s1 (4, 2, 7) 1 4 2 7> s2 = partial (spam, d = 42) # Set the value of d to 42 >>> s2 (1, 2, 3) 1 2 3 42 >>> s2 (3, 2, 3) 3 2 3 42 >>> s3 = partial (spam, 1, 2, d = 42) # a = 1, B = 2, d = 42 >>> s3 (2) 1 2 2 42> s3 (28)

 

2. Add metadata to function parameters

Each parameter in the function declaration can be followed by an annotation expression. If the parameter has a default value, the annotation is placed between the parameter name and the = sign. If you want to annotate the return value, add-> and an expression between) and: at the end of the function declaration.

The expression can be of any type. The most common types of annotations are classes (such as str or int) and strings (such as 'int> 0 ').

>>> Def add (x: int, y: int)-> int :... return x + y... >>> add (2, 4) 6 >>> help (add) Help on function add in module _ main __: add (x: int, y: int) -> int >>> add. _ annotations __{ 'X': <class 'int'>, 'y': <class 'int'>, 'Return ': <class 'int' >}# function annotations are only stored in the annotations attribute of the function.

 

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.