Learning Python in anger - Part 4 - Functions and modules

黄舟
Release: 2016-12-20 16:57:45
Original
1132 people have browsed it

Python functions: In fact, it is very similar to C++, but because it is a weakly typed language (it feels like...), those type declarations are removed, and values ​​are passed instead of references (at least in 2.7) , there is a small difference that def must be added in front to define it (it looks like a macro definition...), the following is an example

def sum(a, b): .....
c = a + b #This part is the statement block of the function
return c #The function ends here, just like C++ PRint sum(1, 2) #Call the function based on the function name and output 1+ The value of 2

There is also a lambda function here, which is very similar to the characteristics of C++11. Give the previous example of the addition function

sum = lambda a, b:a + b                   #This is the definition of the lambda function, with It starts with lambda, followed by the incoming parameters, no matter how many are separated by ",", and then ":" is followed by the expression you want to implement the operation print sum(1, 2)

Python module: This part feels like Java It does matter, but I feel that the module is just a file written together with the header file and implementation in C++. Here is an example

First give the code of the addition function module, if it exists in fun.py in the current directory

#!/usr/bin/pythondef sum(a, b):
c = a + b return c

gives the code of the main function. If it is named test.py and exists in the current directory, use import to import it. Module fun (isn’t this Java...),

#!/usr/bin/pythonimport funprint fun.sum(1, 2)

And sometimes it feels very troublesome, that fun is a and The same thing as the C++ namespace, so you can actually import sum into the current space through the from...import statement, giving the code

#!/usr/bin/pythonfrom fun import sumprint sum(1, 2)

Sometimes there will be road strength problems. For the time being, just make sure that the imported module is in the same directory as the main program. The above is the content of Learning Python in anger - Part 4 - Functions and modules. Please pay attention to more related content. PHP Chinese website (www.php.cn)!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template