博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python * args和** kwargs
阅读量:2538 次
发布时间:2019-05-11

本文共 5573 字,大约阅读时间需要 18 分钟。

Python函数参数 (Python Function Arguments)

Python allows us to define three types of arguments for a function:

Python允许我们为函数定义三种类型的参数:

  1. Formal Arguments, for example def add(a, b)

    形式参数,例如def add(a, b)
  2. Variable number of non-keyworded arguments using *args, for example def add(*args)

    使用* args的可变数量的非关键字参数,例如def add(*args)
  3. Variable number of keyworded arguments or named arguments using **kwargs, for example def add(**kwargs).

    使用** kwargs的可变数量的关键字参数或命名参数,例如def add(**kwargs)

Some important points about function arguments.

有关函数参数的一些重要点。

  • When we define a function arguments, the order should be formal arguments followed by *args and **kwargs.

    当定义函数参数时,顺序应为形式参数,后跟* args和** kwargs。
  • It’s not mandatory to use the names args and kwargs, we can use other names too. However, it’s the convention to use them. It will make your code easy to read and understand.

    使用名称args和kwargs不是强制性的,我们也可以使用其他名称。 但是,使用它们是惯例。 这将使您的代码易于阅读和理解。
  • The args variable is of type . We can pass a tuple as a function argument to map with args.

    args变量的类型为 。 我们可以将元组作为函数参数传递给args进行映射。
  • The kwargs variable is of type . So we can pass a dictionary as an argument to map with kwargs.

    kwargs变量的类型为 。 因此我们可以将字典作为参数传递给kwargs。

为什么我们需要* args和** kwargs? (Why do we need *args and **kwargs?)

Let’s say we have a function to add two numbers:

假设我们有一个将两个数字相加的函数:

def add_two_numbers(a, b):    return a + b

Now we want to extend this to add three numbers. We can’t just change this function because it might be getting used at some other places and it will be a breaking change. So, we introduce another function to add three numbers.

现在我们要扩展它以添加三个数字。 我们不能仅仅更改此功能,因为它可能会在其他地方使用,这将是一个重大突破。 因此,我们引入了另一个函数,将三个数字相加。

def add_three_numbers(a, b, c):    return a + b + c

You see where I am going with this, right? Since we have the option to specify a variable number of arguments for a function, we can define a generic function to add numbers.

你知道我要去哪里了吧? 由于我们可以为函数指定可变数量的参数,因此我们可以定义一个通用函数来添加数字。

Python * args示例 (Python *args example)

Let’s define a generic function to add numbers using *args variables.

让我们定义一个通用函数,以使用* args变量加数字。

def add(*args):    total = 0    for arg in args:        total = total + arg    return totalprint(add(1, 2))print(add(1, 2, 3))print(add(1, 2, 3, 4))

* args和** kwargs是什么类型? (What is the type of *args and **kwargs?)

def zap(*args, **kwargs):    print(type(args))    print(type(kwargs))zap()

Output:

输出:

Python ** kwargs示例 (Python **kwargs example)

Let’s define a function to show the usage of **kwargs variables.

让我们定义一个函数来显示** kwargs变量的用法。

def kwargs_processor(**kwargs):    for k, v in kwargs.items():        print(f'Key={k} and Value={v}')kwargs_processor(name='Pankaj', age=34)kwargs_processor(country='India', capital='New Delhi')

Output:

输出:

Key=name and Value=PankajKey=age and Value=34Key=country and Value=IndiaKey=capital and Value=New Delhi

为* args和** kwargs映射传递元组和字典 (Passing Tuple and Dictionary for *args and **kwargs mapping)

Let’s see how to pass tuple values to map with args and dictionary elements to the kwargs variable.

让我们看看如何将元组值与args和dictionary元素映射到kwargs变量。

t = (10, 30, 60)print(add(*t))d = {'name': 'Pankaj', 'age': 34}kwargs_processor(**d)

Output:

输出:

100Key=name and Value=PankajKey=age and Value=34

Notice the use of * while using a tuple to map its values to args. Similarly, ** is used to map dict elements to the kwargs variable.

注意在使用元组将其值映射到args时使用*。 同样,**用于将dict元素映射到kwargs变量。

何时使用* args和** kwargs (When to use *args and **kwargs)

You can use them in any function where you are expecting a variable number of arguments. However, they are very useful in two specific cases – Simulating a function response, and writing a generic function.

您可以在期望可变数量参数的任何函数中使用它们。 但是,它们在两种特定情况下非常有用-模拟函数响应和编写通用函数。

用* args和** kwargs模拟函数响应 (Simulating a function response with *args and **kwargs)

Let’s say we have an API class defined like this:

假设我们有一个如下定义的API类:

class APIHelper:    def call_api(self, url, input_json):        # some complex logic        return 'complex_response_data'

We can create a test simulator function and map it to the API function to generate a test response.

我们可以创建一个测试模拟器函数并将其映射到API函数以生成一个测试响应。

class MyTestClass:    def test_call_api(self, *args, **kwargs):        return "test_response_data"# Assign API function to use our test functionAPIHelper.call_api = MyTestClass.test_call_api

Let’s see what happens when we use our API functions now.

让我们看看现在使用我们的API函数时会发生什么。

ah = APIHelper()print(ah.call_api())print(ah.call_api(1, url='https://www.journaldev.com', input_json={}))print(ah.call_api(1, 2, url='https://www.journaldev.com'))

Output:

输出:

test_response_datatest_response_datatest_response_data

* args和** kwargs的装饰函数 (Decorator function for *args and **kwargs)

Let’s see how we can define a decorator function to log function variables.

让我们看看如何定义一个装饰器函数来记录函数变量。

def log_arguments(func):    def inner(*args, **kwargs):        print(f'Arguments for args:{args}, kwargs:{kwargs}')        return func(*args, **kwargs)    return inner

Now, we can use this decorator function with any other function to log their arguments to console.

现在,我们可以将此装饰器函数与任何其他函数一起使用,以将其参数记录到控制台。

@log_argumentsdef foo(x, y, z):    return x + y + zsum_ints = foo(1, 2, z=5)print(sum_ints)@log_argumentsdef bar(x, *args, **kwargs):    total = x    for arg in args:        total = total + arg    for key, value in kwargs.items():        total = total + value    return totalsum_ints = bar(1, 2, 3, a=4, b=5)print(sum_ints)

Output:

输出:

Arguments for args:(1, 2), kwargs:{'z': 5}8Arguments for args:(1, 2, 3), kwargs:{'a': 4, 'b': 5}15
. 检出完整的python脚本和更多Python示例。

翻译自:

转载地址:http://mmmzd.baihongyu.com/

你可能感兴趣的文章
哈希(1) hash的基本知识回顾
查看>>
Leetcode 6——ZigZag Conversion
查看>>
dockerfile_nginx+PHP+mongo数据库_完美搭建
查看>>
Http协议的学习
查看>>
【转】轻松记住大端小端的含义(附对大端和小端的解释)
查看>>
设计模式那点事读书笔记(3)----建造者模式
查看>>
ActiveMQ学习笔记(1)----初识ActiveMQ
查看>>
Java与算法之(2) - 快速排序
查看>>
Windows之IOCP
查看>>
机器学习降维之主成分分析
查看>>
CTP2交易所成交回报
查看>>
WebSocket & websockets
查看>>
openssl 升级
查看>>
ASP.NET MVC:通过 FileResult 向 浏览器 发送文件
查看>>
CVE-2010-2883Adobe Reader和Acrobat CoolType.dll栈缓冲区溢出漏洞分析
查看>>
使用正确的姿势跨域
查看>>
AccountManager教程
查看>>
Android学习笔记(十一)——从意图返回结果
查看>>
算法导论笔记(四)算法分析常用符号
查看>>
ultraedit激活
查看>>