From C # To Python -- 3 function and function programming,

Source: Internet
Author: User
Tags define function

From C # To Python -- 3 function and function programming,

In C #, there is no independent function. Only the class (dynamic or static) method is used. It refers to the member used to execute computing or other behaviors in the class. In Python, you can use a method similar to C # To define the dynamic or static member methods of a class, because it supports full object-oriented programming like C. You can also use procedural programming to compile Python programs. At this time, functions and classes in Python can have nothing to do with them, similar to defining and using functions in C language. In addition, Python also supports functional programming. Although its support for functional programming is not as complete as that for languages such as LISP, proper use can improve our work efficiency.

This chapter mainly introduces the definition and usage of functions in Python in the process programming mode. We will discuss how to use functions in Object-Oriented Programming in the next chapter. In addition, I will briefly introduce the function programming functions in Python.

3.1 Function Definition

Function definition is the most basic abstract behavior code and the initial method of software reuse. In Python, Function Definition statements include the def keyword, function name, brackets, parameters (optional), and colons. The following are some simple function definition statements:

1 #-*-coding: UTF-8 -*-
2 # define a function without parameters or returned values
3 def F1 ():
4 print 'Hello kitty! '
5 # define a function with parameters and a returned value
6 def F2 (x, y ):
7 a = x + y
8 return
9 # define a function with multiple return values. Use commas to separate different return values. The returned result is a tuple.
10 def F3 (x, y ):
11 a = x/y
12 B = x % y
13 return a, B

You may have noticed that Python does not constrain the parameter type when defining a function. It supports generic programming in the simplest form. You can enter any type of data as a parameter, as long as these types support internal operations of the function (of course, you need to do some type judgment, Exception Processing and other work within the function if necessary ).

3.2 differences between function parameter 3.2.1 C # And Python in function parameter definition

There are four types of method parameters in C:

(1) Value parameters do not contain any Modifier
(2) The referenced parameter is declared with a ref modifier (there is no corresponding definition in Python)
(3) output parameters are declared with the out modifier (this is not required in Python, because the function can have multiple return values)
(4) array parameters are declared with params Modifiers

There are also four types of function parameters in Python:

(1) f (arg1, arg2,...) is the most common function definition method.
(2) f (arg1 = value1, arg2 = value2 ,..., argN = valueN) This method provides the default value for the parameter, and the parameter order can be changed when the function is called, also known as the keyword parameter.
(3) f (* arg) arg represents a tuple. Similar to the params modifier in C #, multiple parameters can be accepted.
(4) f (** arg) input parameters are stored in dict named arg in the function. To call these parameters, use f (a1 = v1, a2 = v2) format.

We can see that the two biggest differences between the Python function parameter definition and C # Are the support for keyword parameters and dictionary parameters.

 

3.29 update: As prompted by JeffreyZhao, C #4.0 supports naming parameters (I .e., keyword parameters) and optional parameters (I .e., the default parameter values). For details, see the following on the sashboard: C #4.0 new features: optional parameters, named parameters, Dynamic. I would like to express my gratitude to both of you.

 

3.2.2 keyword Parameters

Keyword parameters make it easier to call Python functions with many parameters and some parameters with default values, it is also an important way to implement function overloading in Python (to the class and object section, let's talk about this problem in detail ). The following example illustrates how to define and call a function with a keyword parameter (derived from Guido van rosum's getting started with Python, including the following examples ):

1 def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
2 print "-- This parrot wouldn't", action,
3 print "if you put", voltage, "Volts through it."
4 print "-- Lovely plumage, the", type
5 print "-- It's", state, "!"


You can call it in the following ways:

1 parrot (1000) # Default Value
2 parrot (action = 'vooom ', voltage = 1000000) # keyword, default value, variable order
3 parrot ('a thousand', state = 'pushing up the daisies ') # location parameter, default value, keyword
4 parrot ('a million', 'bereft of life', 'jump ') # location parameter, default value


However, the following call methods are incorrect:

1 parrot () # non-default parameters are not provided
2 parrot (voltage = 5.0, 'Demo') # A non-Keyword parameter appears after the keyword Parameter
3 parrot (110, voltage = 220) # provide repeated parameter values
4 parrot (actor = 'John Cleese ') # unknown keyword
3.2.3 dictionary Parameters

If there is a ** name parameter in the form parameter table, this form parameter can receive a dictionary when called. The dictionary contains all key parameters that do not match any form parameter. For example, the following function:

1 def cheeseshop(**keywords):
2 for kw in keywords.keys(): print kw, ':', keywords[kw]


It can be called as follows:

1 cheeseshop(client='John Cleese',
2 shopkeeper='Michael Palin',
3 sketch='Cheese Shop Sketch')


Result:

Client: John Cleese
Shopkeeper: Michael Palin
Sketch: Cheese Shop Sketch

3.2.4 sequence of function parameter calls

When a Python function is called, the parameter writing sequence is: Non-Keyword parameter, keyword parameter, tuples parameter, and dictionary parameter. Remember the following rules:

* Assign non-Keyword parameters by location
* Assign a keyword parameter by matching the variable name
* Other non-Keyword parameters are allocated to * name tuples.
* Other additional keyword parameters are allocated to ** name dictionaries.
* Use the default value to assign parameters that are not allocated during the call.

In general, non-Keyword parameters in the real parameter table are prior, and the keyword name must be the name of the form parameter. You can call the parameter in the form of a keyword parameter if there are any default values. Each form parameter can only correspond to one real parameter at most. Therefore, the form parameter that has been passed in by the location parameter cannot be used as a keyword parameter in the same call.

In short, because Python's function parameter definitions and calling methods are too flexible, it is easy to confuse people at first. However, you will find Python easier.

3.3 function documentation

In C #, you can use the XML mark of the document to annotate the function. In this way, in IDE such as VS, after entering the function name, you will be prompted for descriptions of the function functions, parameters, and return values, convenience for function callers. Similar functions are available in Python, namely, Docstrings ). However, the Python document string is not as rich as the XML mark of the document in C #, which is basically equivalent to the <summary> mark in C, let's take a look at the following example (introduced in concise Python tutorial):

 1     def printMax(x, y):
2 '''Prints the maximum of two numbers.
3
4 The two values must be integers.'''
5 x = int(x) # convert to integers, if possible
6   y = int(y)
7
8 if x > y:
9 print x, 'is maximum'
10 else:
11 print y, 'is maximum'
12
13 printMax(3, 5)
14 print printMax.__doc__

Output

$ Python func_doc.py
5 is maximum
Prints the maximum of two numbers.

The two values must be integers.

In the preceding function, the string of the first logical line is the document string of this function. A document string is a multi-line string whose first line starts with an uppercase letter and ends with a full stop. The second line is a blank line, and the first line is a detailed description of the object's call method, parameter description, return value, and other details.

You can use _ doc _ (pay attention to double underscores) to call the document string attribute of the printMax function (which belongs to the function name. Remember that Python regards everything as an object, including this function ). It is equivalent to reading the description of a function using the Python built-in function help. Many Python ides rely on function documentation strings for Intelligent Code prompts. Therefore, we should develop the habit of writing document strings when writing functions.

3.4 function Programming

Python includes some common functions in function programming languages and Lisp, such as anonymous functions, high-level functions, and list meanings, I have introduced the last question in "2 operators, expressions, and process control". This chapter only introduces anonymous and high-level functions.

3.4.1 anonymous Functions

Lambda functions are anonymous functions used to define function objects without names. In Python, lambda can only contain expressions: lambda arg1, arg2...: expression. The lambda keyword is followed by a comma-separated list of form parameters. The colon is followed by an expression, and the result of the expression evaluation is the return value of lambda.

Although lambda abuse will seriously affect code readability, It is of practical significance to use lambda to reduce keyboard percussion when appropriate. For example, data is used for sorting. sort (key = lambda o: o. year)

1 def get_year(o):
2 return o.year
3 func=get_year(o)
4 data.sort(key=func)

It is much more convenient. (Refer to "Cute Python")

 

3.29 update: refresh the contents of the anonymous function in C # according to the JeffreyZhao prompt (This part mainly refer to MSDN, see http://msdn.microsoft.com/zh-cn/library/bb882516.aspx ):

The anonymous function is also available in C. In C #1.0, the delegate instance is created by explicitly initializing the delegate using a method defined elsewhere in the code. C #2.0 introduces the concept of anonymous methods, as a way to compile unnamed inline statement blocks that can be executed in a delegate call. C #3.0 introduces Lambda expressions, which are similar to anonymous methods but more expressive and concise. These two functions are collectively referred to as "anonymous functions ". Generally, Lambda expressions should be used for. NET 3.5 and later applications.

Lambda expressions can contain expressions and statements and can be used to create a delegate or expression directory tree type. All Lambda expressions use the Lambda operator =>. The left side of the operator is the input parameter (if any), and the right side contains the expression or statement block. You can assign this expression to the delegate type as follows:

 

1 delegate int del(int i);
2 del myDelegate = x => x * x;
3  int j = myDelegate(5); //j = 25

 

3.4.2 High-Order Functions

High Order is the basis of functional programming. Common High Order functions include:
(1) ing, that is, applying algorithms to every element in the container, and merging the returned values into a new container.
(2) filter, apply the algorithm to every element in the container, and combine the elements that return the true value into a new container.
(3) Merge, apply the algorithm (which may carry an initial value) to each element in the container in sequence, and use the return value as one of the parameters for the next calculation, and then calculate the value with the next element, until a general result is obtained.

Python uses three built-in functions: map, filter, and reduce to implement the above three high-level functions. This document does not describe the usage of these three functions in detail. It only provides the sample code (derived from the Python map, filter, and reduce functions:

1
2 # coding: UTF-8
3
4 def map_func (lis ):
5 return lis + 1
6
7 def filter_func (li ):
8 if li % 2 = 0:
9 return True
10 else:
11 return False
12
13 def performance_func (li, lis ):
14 return li + lis
15
16 li = [1, 2, 4, 5]
17
18 map_l = map (map_func, li) # add all the numbers in li to + 1
19 filter_l = filter (filter_func, li) # obtain the divisible by 2 in li
20 cece_l = reduce (reduce_func, li) #1 + 2 + 3 + 4 + 5
21
22 print map_l
23 print filter_l
24 print performance_l

The running result is as follows:
C: \> python test1.py
[2, 3, 4, 5, 6]
[2, 4]
15

3.29 update: As prompted by JeffreyZhao, C # can delegate most functions of function programming. But to be honest, I have never used it that way, because I have come into contact with the function programming concept that is only available after Python. I used to write a program in C # without the idea of function programming, although you know that "delegate allows passing methods as parameters ". However, it is estimated that the C # experts are much clearer than me, so I will not write it around.

 

Conclusion 3.5

This chapter discusses the definition and usage of functions in Python. The main points are as follows:

(1) define functions using def keywords, function names, Parentheses, parameters (optional), and colons in Python (remember to indent the function body ), A function can have 0, 1, or multiple return values;
(2) A Python-defined function does not need or cannot specify the parameter type. It is inherently generic;
(3) Python supports four types of parameters: common parameters, keyword parameters, tuples, and dictionary parameters. Learn to use them flexibly;
(4) Docstrings are used to annotate Python functions for introspection functions and IDE calls;
(5) lambda keywords are used to define anonymous functions. They only support expressions. In some cases, the amount of code written can be simplified, but do not abuse them;
(6) Python uses three built-in functions: map, filter, and reduce to implement the ing, filtering, and merging functions in function programming, however, note that map and filter can be replaced by list content (see Chapter 2nd ).

 

For more information, see:

[1] This Chapter provides many references to Guido van Rossum, the father of Python, and a classic Chinese tutorial "Cute Python". I recommend these two books to you again, I would like to express my appreciation to the author and the translator.

[2] Due to space limitations and depth, some important topics in Python functions are not discussed, such as scope, function nesting, and recursion. In my opinion, do not make things too complicated first, it is always good to take a long time. If you have learned the content of this chapter, we recommend that you read "go deep into Python". This book has the most in-depth discussions on many topics (I have read many books.

 

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.