Python functions: In fact, it is very similar to C + +, but because it is a weak type of language (it feels like ...). ), the declaration of those types are removed, the value is not a reference (at least 2.7 is), a little bit small difference is the first must be defined by DEF (like a macro definition). ), show examples below
def sum (A, B): #sum为函数名, note the colon ...
c = A + b #这一部分是函数的语句块
Return c #到这里函数就结束了, same as C + + print sum (1, 2) #根据函数名调用函数, output 1+2 value
There is also a lambda function, similar to C++11 's, giving an example of the preceding addition function
sum = lambda A, b:a + b #这就是lambda函数的定义, starts with lambda, and then passes in parameters, regardless of how many are separated by "," and then ":" After the expression that you want to implement for the operation print sum (1, 2)
Python module: This part of the feeling is related to Java, but the module gives me the feeling is C + + inside the header file and implementation of the file written together, the following examples
The code for the module of the addition function is given first, if there is a fun.py inside the current directory
#!/usr/bin/pythondef sum (A, B):
c = A + B return c
Given the code of the main function, if the current directory is named test.py, import the module fun (this is not Java ...). ),
#!/usr/bin/pythonimport Funprint fun.sum (1, 2)
And sometimes feel very troublesome, that fun is a C + + namespace The same thing, so you can actually put sum through the From...import statement into the current space, give the code
#!/usr/bin/pythonfrom Fun Import Sumprint sum (1, 2)
Sometimes there will be road problems, this is to ensure that the import module in and the main program in a directory is good
The above is the fourth chapter of Nu python---function and module content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!