Home Backend Development Python Tutorial Python中函数的多种格式和使用实例及小技巧

Python中函数的多种格式和使用实例及小技巧

Jun 10, 2016 pm 03:15 PM
python function Example Tips Format

这里先解释一下几个概念
- 位置参数:按位置设置的参数,隐式用元组保存对应形参.平时我们用的大多数是按位置传参.比如有函数def func(a,b,c),调用func(1,2,3).即a=1,b=2,c=3
- 关键字参数:可以通过关键字设置参数,不用关心参数位置,隐式用字典保存形参.比如有函数def func(a,b,c),调用func(b=1,c=2,a=3),即a=3,b=1,c=2

普通格式

复制代码 代码如下:

def func(opt_args):
    ...
    return value

带收集位置参数的函数

格式如下

复制代码 代码如下:

def func(*params):
    ...
    return value

用法

使用函数时,不用限制传参的个数,*params会自动收集传入的参数作为一个元组.

实例

复制代码 代码如下:

def  func(*params):
    print params

a = [1,2,3,4]
b = 'hello'
c = 3
func(a, b, c)

输出

复制代码 代码如下:

([1, 2, 3, 4], ‘hello', 3)

带收集关键字参数的函数

格式如下

复制代码 代码如下:

def func(**params):
    ...
    return value

用法
按关键字传参时,**params会自动收集传入的参数作为一个字典.

实例

复制代码 代码如下:

def  func(**params):
    print params
func(a=1, b=2, c=3)

输出
复制代码 代码如下:

{‘a': 1, ‘c': 3, ‘b': 2}

函数特殊用法

默认参数

格式

复制代码 代码如下:

def func(a = 1, b = 2)

等号(=)号是默认值,调用函数时可以不用传参给默认参数.
实例
复制代码 代码如下:

def  func(a = 1, b = 2):
    print a, b 
func(a=3)

输出
复制代码 代码如下:

3 2

函数可以返回多个值

格式

复制代码 代码如下:

return a, b, c

实例
复制代码 代码如下:

def  func(a = 1, b = 2):
    return a, b

print func(a=3)


输出
复制代码 代码如下:

(3, 2)

内嵌函数和闭包

格式

复制代码 代码如下:

def foo()    #外部函数
    def bar()    #内嵌函数
        ....
    ....

如果内嵌函数引用了外部函数的变量(包括外部函数参数),这个引用的变量称为自由变量, 那么称这个内嵌函数是闭包.再来看看专业的解释:闭包(Closure)是词法闭包(Lexical Closure)的简称,是引用了自由变量的函数。这个被引用的自由变量将和这个函数一同存在,即使已经离开了创造它的环境也不例外。

实例

复制代码 代码如下:

def foo(a, b):
    x = 4
    def bar():
        return x * a + b;
    return bar

f1= foo(1, 2)
f2= foo(2, 3)

print f1(), f2()


输出
复制代码 代码如下:

6 11

传递函数

Python一切皆对象,函数这一语法结构也是一个对象, 可以将函数名作为参数传递
格式

复制代码 代码如下:

def bar(*param1, **param2):
    ....

def foo(bar, *param1, **param2):
    bar(*param1, **param2)


实例
复制代码 代码如下:

def bar(*param1, **param2):
    print param1
    print param2

def foo(bar, *param1, **param2):
    bar(*param1, **param2)

foo(bar,  1, 2, 3,  a = 111, b = 222, c = 333)


输出
复制代码 代码如下:

(1, 2, 3)
{‘a': 111, ‘c': 333, ‘b': 222}

匿名函数与lambda

lambda语法可以创建一个匿名的函数,主要作用是简化书写,是一种语法糖.
- 格式

复制代码 代码如下:

lambda [arg1[, arg2, … argN]] : expression

实例
复制代码 代码如下:

def foo(x, y):
    return x + y
print  "call foo function, result is: ", foo(3, 4)

bar = lambda x = 2, y = 3 : x + y
print  "call lambda fucntion, result is:", bar(3,4)


输出
复制代码 代码如下:

call foo function, result is: 7
call lambda fucntion, result is: 7
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the conversion speed fast when converting XML to PDF on mobile phone? Is the conversion speed fast when converting XML to PDF on mobile phone? Apr 02, 2025 pm 10:09 PM

The speed of mobile XML to PDF depends on the following factors: the complexity of XML structure. Mobile hardware configuration conversion method (library, algorithm) code quality optimization methods (select efficient libraries, optimize algorithms, cache data, and utilize multi-threading). Overall, there is no absolute answer and it needs to be optimized according to the specific situation.

How to convert XML files to PDF on your phone? How to convert XML files to PDF on your phone? Apr 02, 2025 pm 10:12 PM

It is impossible to complete XML to PDF conversion directly on your phone with a single application. It is necessary to use cloud services, which can be achieved through two steps: 1. Convert XML to PDF in the cloud, 2. Access or download the converted PDF file on the mobile phone.

What is the function of C language sum? What is the function of C language sum? Apr 03, 2025 pm 02:21 PM

There is no built-in sum function in C language, so it needs to be written by yourself. Sum can be achieved by traversing the array and accumulating elements: Loop version: Sum is calculated using for loop and array length. Pointer version: Use pointers to point to array elements, and efficient summing is achieved through self-increment pointers. Dynamically allocate array version: Dynamically allocate arrays and manage memory yourself, ensuring that allocated memory is freed to prevent memory leaks.

Is there a mobile app that can convert XML into PDF? Is there a mobile app that can convert XML into PDF? Apr 02, 2025 pm 09:45 PM

There is no APP that can convert all XML files into PDFs because the XML structure is flexible and diverse. The core of XML to PDF is to convert the data structure into a page layout, which requires parsing XML and generating PDF. Common methods include parsing XML using Python libraries such as ElementTree and generating PDFs using ReportLab library. For complex XML, it may be necessary to use XSLT transformation structures. When optimizing performance, consider using multithreaded or multiprocesses and select the appropriate library.

Recommended XML formatting tool Recommended XML formatting tool Apr 02, 2025 pm 09:03 PM

XML formatting tools can type code according to rules to improve readability and understanding. When selecting a tool, pay attention to customization capabilities, handling of special circumstances, performance and ease of use. Commonly used tool types include online tools, IDE plug-ins, and command-line tools.

How to convert XML to PDF on your phone? How to convert XML to PDF on your phone? Apr 02, 2025 pm 10:18 PM

It is not easy to convert XML to PDF directly on your phone, but it can be achieved with the help of cloud services. It is recommended to use a lightweight mobile app to upload XML files and receive generated PDFs, and convert them with cloud APIs. Cloud APIs use serverless computing services, and choosing the right platform is crucial. Complexity, error handling, security, and optimization strategies need to be considered when handling XML parsing and PDF generation. The entire process requires the front-end app and the back-end API to work together, and it requires some understanding of a variety of technologies.

How to open xml format How to open xml format Apr 02, 2025 pm 09:00 PM

Use most text editors to open XML files; if you need a more intuitive tree display, you can use an XML editor, such as Oxygen XML Editor or XMLSpy; if you process XML data in a program, you need to use a programming language (such as Python) and XML libraries (such as xml.etree.ElementTree) to parse.

How to convert xml into pictures How to convert xml into pictures Apr 03, 2025 am 07:39 AM

XML can be converted to images by using an XSLT converter or image library. XSLT Converter: Use an XSLT processor and stylesheet to convert XML to images. Image Library: Use libraries such as PIL or ImageMagick to create images from XML data, such as drawing shapes and text.

See all articles