Python的*args和**kwargs

简单来说args表示的是一个元组,而kwargs表示的是一个字典

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 tuple. We can pass a tuple as a function argument to map with args.
    args变量的类型为tuple 。 我们可以将元组作为函数参数传递给args进行映射。
  • The kwargs variable is of type dict. So we can pass a dictionary as an argument to map with kwargs.
    kwargs变量的类型为dict 。 因此我们可以将字典作为参数传递给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 example

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


def add(*args):
    total = 0
    for arg in args:
        total = total + arg
    return total


print(add(1, 2))
print(add(1, 2, 3))
print(add(1, 2, 3, 4))

What is the type of *args and **kwargs?


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


zap()

Output:


<class 'tuple'>
<class 'dict'>

Python **kwargs example

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


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=Pankaj
Key=age and Value=34
Key=country and Value=India
Key=capital and Value=New Delhi

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.


t = (10, 30, 60)
print(add(*t))

d = {'name': 'Pankaj', 'age': 34}
kwargs_processor(**d)

Output:


100
Key=name and Value=Pankaj
Key=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.

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 decorator function.

Simulating a function response with *args and **kwargs

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


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.


class MyTestClass:

    def test_call_api(self, *args, **kwargs):
        return "test_response_data"

# Assign API function to use our test function
APIHelper.call_api = MyTestClass.test_call_api

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


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_data
test_response_data
test_response_data

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_arguments
def foo(x, y, z):
    return x + y + z


sum_ints = foo(1, 2, z=5)
print(sum_ints)


@log_arguments
def bar(x, *args, **kwargs):
    total = x
    for arg in args:
        total = total + arg
    for key, value in kwargs.items():
        total = total + value
    return total


sum_ints = bar(1, 2, 3, a=4, b=5)
print(sum_ints)

Output:

Arguments for args:(1, 2), kwargs:{'z': 5} 8 Arguments for args:(1, 2, 3), kwargs:{'a': 4, 'b': 5} 15

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
YOLO系列是基于深度学习的端到端实时目标检测方法。 PyTorch版的YOLOv5轻量而性能高,更加灵活和易用,当前非常流行。 本课程将手把手地教大家使用labelImg标注和使用YOLOv5训练自己的数据集。课程实战分为两个项目:单目标检测(足球目标检测)和多目标检测(足球和梅西同时检测)。 本课程的YOLOv5使用ultralytics/yolov5,在Windows系统上做项目演示。包括:安装YOLOv5、标注自己的数据集、准备自己的数据集、修改配置文件、使用wandb训练可视化工具、训练自己的数据集、测试训练出的网络模型和性能统计。 希望学习Ubuntu上演示的同学,请前往 《YOLOv5(PyTorch)实战:训练自己的数据集(Ubuntu)》课程链接:https://edu.csdn.net/course/detail/30793  本人推出了有关YOLOv5目标检测的系列课程。请持续关注该系列的其它视频课程,包括:《YOLOv5(PyTorch)目标检测实战:训练自己的数据集》Ubuntu系统 https://edu.csdn.net/course/detail/30793Windows系统 https://edu.csdn.net/course/detail/30923《YOLOv5(PyTorch)目标检测:原理与源码解析》课程链接:https://edu.csdn.net/course/detail/31428《YOLOv5目标检测实战:Flask Web部署》课程链接:https://edu.csdn.net/course/detail/31087《YOLOv5(PyTorch)目标检测实战:TensorRT加速部署》课程链接:https://edu.csdn.net/course/detail/32303《YOLOv5目标检测实战:Jetson Nano部署》课程链接:https://edu.csdn.net/course/detail/32451《YOLOv5+DeepSORT多目标跟踪与计数精讲》课程链接:https://edu.csdn.net/course/detail/32669《YOLOv5实战口罩佩戴检测》课程链接:https://edu.csdn.net/course/detail/32744《YOLOv5实战中国交通标志识别》课程链接:https://edu.csdn.net/course/detail/35209《YOLOv5实战垃圾分类目标检测》课程链接:https://edu.csdn.net/course/detail/35284       
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值