From C # to python--3 functions and function programming

Source: Internet
Author: User
Tags uppercase letter

There is no independent function in C #, only the concept of a class (dynamic or Static) method, which refers to a member of a class that performs calculations or other behavior. In Python, you can define a dynamic or static member method of a class in a way similar to C #, because it supports full object-oriented programming as it does in C #. You can also write Python programs programmatically, where functions in Python have nothing to do with classes, similar to the way C defines and uses functions. In addition, Python supports functional programming, although its support for functional programming is not as complete as Lisp and other languages, but proper use can improve the efficiency of our work.

This chapter focuses on the definition and use of functions in Python in process programming mode, and we will discuss the use of functions in object-oriented programming in the next chapter. In addition, I will briefly describe the function programming functions in Python.

3.1 Definition of function

function definition is the most basic behavior abstract code, and it is the primary way of software reuse. The definition statement for a function in Python consists of the DEF keyword, the function name, the parentheses, the argument (optional), and the colon: Here are a few simple function definition statements:

1 #-*-Coding:utf-8-*-
2 #定义没有参数, and no function to return a value
3 def F1 ():
4 print ' Hello kitty! '
5 #定义有参数和一个返回值的函数
6 def F2 (x, y):
7 a = x + y
8 return a
9 #定义有多个返回值的函数, separate the return values with commas, and return the result as a tuple
Ten def F3 (x, y):
One a = x/y
B = x%y
Return a, b

As you may have noticed, Python does not have a type of constraint parameter when defining a function, and it supports generic programming in its simplest form. You can enter any type of data as a parameter, as long as these types support operations inside the function (of course, you need to do some type judgments, exception handling, etc.) within the function.

3.2 Parameters of the function 3.2.1 C # and Python differences in function parameter definitions

There are four types of parameters for methods in C #:

(1) value parameter does not contain any modifiers
(2) The reference parameter is declared with a ref modifier (there is no corresponding definition in Python)
(3) Output parameters declared with out modifier (not required in Python, because functions can have multiple return values)
(4) Array parameters are declared with the params modifier

There are also four types of function parameters in Python:

(1) F (arg1,arg2,...) This is the most common way to define a function
(2) F (arg1=value1,arg2=value2,..., Argn=valuen) This method provides a default value for the parameter, and the parameter order can vary, also known as the keyword argument, when the function is called.
(3) F (*arg) arg represents a tuple, similar to the params modifier in C #, and can accept multiple arguments
(4) F (**arg) The parameters passed in inside the function are stored in dict with the name ARG, which needs to be called in the form of F (a1=v1,a2=v2).

As you can see, the maximum two differences between Python function parameter definitions and C # are support for keyword parameters and dictionary parameters.

3.29 Update: According to Jeffreyzhao hint, C # 4.0 already supports named parameters (that is, keyword parameters) and optional parameters (i.e. parameter default values), details on the sashimi blog: "c#4.0 new features: Optional parameters, named parameters, Dynamic." Thank you here for the two-bit.

3.2.2 Keyword Parameters

The keyword parameter allows us to invoke a Python function that has many parameters, while some parameters have default values, and is also an important means for Python to implement function overloading (the problem is detailed in the class and object sections). The following example shows how to define and invoke a function with keyword parameters (from Guido van Rossum, "Getting Started with Python," including a few examples later):

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, "!"


This can be called in several ways:

1 Parrot (+)                        # Default value
2 Parrot (action = ' vooooom ', voltage = 1000000) # keyword, default value, variable order
3 Parrot (' A thousand ', state = ' Pushing up the Daisies ') # position parameter, default value, keyword
4 Parrot (' A million ', ' bereft of life ', ' jump ') # positional parameters, default values


However, the following methods of invocation are incorrect:

1 Parrot ()                     # non-default parameters not provided
2 Parrot (voltage=5.0, ' dead ') # keyword argument followed by a non-keyword argument
3 Parrot (voltage=220) # parameter values are provided repeatedly
4 Parrot (actor= ' John Cleese ') # unknown keyword
3.2.3 Dictionary Parameters

If there is a formal parameter in the formal parameter list that has a shape of **name, the parameter can receive a dictionary when called, and the dictionary contains all the keyword parameters that do not match any formal parameters. 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 ')


The results show:

Client:john Cleese
Shopkeeper:michael Palin
Sketch:cheese Shop Sketch

3.2.4 the order of function argument calls

When calling the Python function, the parameters are written in the following order: Non-keyword parameter, keyword parameter, tuple parameter, dictionary parameter. Keep in mind the following rules:

* Assign non-keyword parameters by location
* Assigning keyword parameters by matching variable names
* Other additional non-keyword parameters are assigned to the *name tuple
* Other additional keyword parameters are assigned to the **name dictionary
* Assigned to parameters that are not allocated at call time with default values

In general, the argument table in the non-keyword parameter before the keyword argument after the keyword name must be a formal parameter name. A parameter has no default value that can be called in the form of a keyword argument. Each parameter can have at most one argument, so a formal parameter that has been passed into a value by a positional parameter cannot be used as a keyword parameter in the same call.

In short, since Python's function parameters are defined and invoked in a way that is too flexible, it is easy to get people dizzy at first. But you can take it slow, and you'll find the simplicity of Python more and more.

3.3 Function Documents

In C #, you can annotate a function with the document XML tag, so that in the IDE such as VS, you will be prompted with a description of function, parameter, and return value, etc., to facilitate the caller of the function. In Python, there is a similar function, the document string (docstrings). But the Python document string is not as rich as the document XML tag in C #, basically the same as the <summary> tag in C #, let's take a look at one example (from the Concise Python tutorial):

1     def printmax (x, y):
2 "Prints The maximum of the numbers.

4 The values must be integers. "
5 x = Int (x) # Convert to integers, if possible
6 y = Int (y)

8 if x > y:
9 print x, ' is maximum '
Ten Else:
print y, ' is maximum '

Printmax (3, 5)
14

Output

$ python func_doc.py
5 is maximum
Prints the maximum of the numbers.

The values must be integers.

In the above function, the string of the first logical line is the document string for this function. The Convention for a document string is a multiline string whose first line begins with an uppercase letter and ends with a period. The second line is a blank line, starting from the third line is a detailed description, describing the object invocation method, parameter description, return value and other specific information.

You can use __DOC__ (note double underline) to invoke the document string property of the Printmax function (which is the name of the function, remember that Python takes everything as an object, including this function). It is equivalent to reading the description of the function with the Python built-in function help (). Many of the Python Ides also rely on the function's document string for smart hints, so we should develop the habit of writing a document string when writing a function.

3.4 Function Programming

Python adds some features that are common in functional programming languages and Lisp, such as anonymous functions, higher order functions, and list connotations, and I've covered the last question in "2 operators, expressions, and Process Control", which describes only anonymous and higher-order functions.

3.4.1 Anonymous functions

A lambda function is an anonymous function used to define a function object without a name. In Python, a lambda can only contain an expression: Lambda arg1, arg2 ...: expression. The Lambda keyword is followed by a comma-separated list of formal parameters, followed by an expression, and the result of the expression evaluation is the return value of the lambda.

While the misuse of lambda can seriously affect code readability, using lambda at the appropriate time to reduce the keystroke of the keyboard is of practical significance, such as when sorting, using Data.sort (Key=lambda o:o.year) is clearly better than

1 def get_year (o):
2 return O.year
3 Func=get_year (O)
4 Data.sort (Key=func)

Much more convenient. (from "Cute Python")

3.29 Update: Rearrange the contents of anonymous functions in C # based on Jeffreyzhao tips (This section mainly refers to MSDN, see Http://msdn.microsoft.com/zh-cn/library/bb882516.aspx):

There are also anonymous function functions in C #. In C # 1.0, an instance of a delegate is created by explicitly initializing the delegate by using a method defined elsewhere in the code. C # 2.0 introduces the concept of an anonymous method as a way to write an unnamed inline statement block that can be executed in a delegate invocation. C # 3.0 introduces a lambda expression that is similar to the concept of an anonymous method, but more expressive and concise. These two functions are collectively referred to as "anonymous functions". Typically, applications that target. NET 3.5 and later should use LAMBDA expressions.

A LAMBDA expression can contain expressions and statements, and can be used to create delegates or expression tree types. All lambda expressions use the lambda operator =>, the left side of the operator is the input parameter (if any), and the right side contains an expression or a block of statements. You can assign this expression to a 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 Higher order functions

Higher order functions (high order) are the basis of functional programming, and the high-order functions commonly used are:
(1) Mapping, that is, the algorithm is applied to each element in the container, the return value is merged into a new container.
(2) filtering, applying the algorithm to each element in the container, merging the elements of the return value into a new container.
(3) Merging, the algorithm (which may carry an initial value) is applied sequentially to each element in the container, and the return value is evaluated as one of the parameters in the next step, and then calculated with the next element until a total result is obtained.

Python uses the map, filter, reduce three built-in functions to achieve the above three kinds of higher function functions. This article does not describe the usage of these three functions in detail, only the sample code they use (from the Python map, filter, reduce function), please carefully understand:


2 #coding: Utf-8
3
4 def map_func (LIS):
5 return lis + 1

7 def Filter_func (LI):
8 If Li% 2 = = 0:
9 return True
Ten Else:
return False
12
def reduce_func (Li, Lis):
return Li + Lis
15
Li = [1,2,3,4,5]

map_l = Map (Map_func, Li) #将li中所有的数都 +1
filter_l = Filter (Filter_func, Li) #得到li中能被2整除的
reduce_l = reduce (Reduce_func, Li) #1 +2+3+4+5
21st
Print map_l
Print filter_l
Print reduce_l

The results of the operation are as follows:
C:\>python test1.py
[2, 3, 4, 5, 6]
[2, 4]
15

3.29 Update: According to Jeffreyzhao hints, C # can use delegates to implement most functions of function programming. But to be honest, I didn't use it, because it was a function programming concept that came into contact with Python, and previously written in C # without the idea of functional programming, although it was known that "delegates allow methods to be passed as parameters." But the detailed estimates of the C # master than I want to be more clear, I will not write.

3.5 Summary

This chapter discusses the definition and use of functions in Python, with the following key points:

(1) Python defines a function with the DEF keyword, function name, parentheses, arguments (optional), and a colon (to remember that the function body is indented), and the function can have 0, 1, or more return values;
(2) Python-defined functions do not need (and cannot) specify parameter types, which are inherently generic;
(3) Python supports (single or simultaneous use) common parameters, keyword parameters, tuple parameters and dictionary parameters four types of parameters, please learn to use them flexibly;
(4) The document string (docstrings) is used to provide comments on Python functions for the function of introspection and the invocation of the IDE;
(5) The Lambda keyword is used to define an anonymous function, which only supports expressions, and in some cases simplifies the amount of code written, but not misused;
(6) Python uses map, filter, and reduce three built-in functions to map, filter, and merge three higher-order function functions in function programming, but note that map and filter can be substituted with a list connotation (see Chapter 2nd).

Further reading for reference:

[1] The content of this chapter is more reference to Python's father Guido van Rossum's "Introduction to Python" and a domestic classic tutorial "lovely Python", once again to recommend these two books, here to the author and translator Thank you.

[2] limited to space and depth, some important topics in Python functions are not discussed, such as scope, function nesting, recursion, etc., my view is not to make things too complicated, slowly always good. If you have learned the contents of this chapter, it is recommended that you read more about "deep Python", a book that discusses many topics in depth (I read many books).

From C # to python--3 functions and function programming

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.