简体   繁体   English

在python中使用*或**有什么好处吗?

[英]Is there any benefits for using * or ** in python?

Lets say we have this code.. 可以说我们有这段代码。

def test(**test):
    print test
def test2(test):
    print test

test(test=1, asterisk=2)
t = {"test":1, "asterisk":2}
test2(t)

test and test2 function will print out the same result. test和test2函数将打印出相同的结果。

What are some benefits for using ** over passing a dictionary? 与通过字典相比,使用**有什么好处?

If we take a look at your example: 如果我们看一下您的示例:

test(test=1, asterisk=2)

is more readable than

t = {"test":1, "asterisk":2}
test2(t)

or 要么

test2({"test":1, "asterisk":2})

So if you have a function that can accept a variable number of variably named arguments, that's the most readable way of doing it. 因此,如果您有一个函数可以接受可变数量的变量命名参数,则这是最易读的方法。

It works the other way too: 它也以另一种方式起作用:

def add(a, b):
    return a + b
params = { "b": 5, "a": 6}
print(add(**params))

11 11

*args will give you a variable number of arguments: * args将为您提供可变数量的参数:

def min(*args):
    min = None
    for v in args:
        if min is None or v < min:
            min = v
    return min

print(min(1, 7, 8, 9, 2, 1, 0))

0 0

This also works the other way: 这也可以用另一种方式工作:

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

t = [5, 6]
print(add(*t))

11 11

Both are used when wrapping other functions, like when creating function decorators: 两者都用于包装其他函数,例如创建函数装饰器时:

def log_call(f):
    def logged(*args, **kwargs):
        print("Called {}".format(f.__name__))
        return f(*args, **kwargs)
    return logged

class A:
    @log_call
    def add_two_numbers(self):
        return 1 + 2

print(A().add_two_numbers())

Called add_two_numbers 称为add_two_numbers
3 3

It's pretty essential when writing decorators. 编写装饰器时,这非常重要。 Ideally you want the decorator to work on functions with differing arguments. 理想情况下,您希望装饰器处理带有不同参数的函数。

def mydecorator(func):
    def new_func(*args, **kwargs):
        #do something here...
        return func(*args, **kwargs)
    return new_func

used in Passing parameters with dict 用于通过dict传递参数

let us consider a method 让我们考虑一种方法

def foo(a=10,b=20):
   return a+b

Now you can pass parameters like this 现在您可以像这样传递参数

d={'a'=20,'b'=30}

print foo(**d)

with ** Python dynamically pass the values to respective Parameters 使用** Python将值动态传递给各自的参数

output : 50

String Foramtting 琴弦打孔

coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
print 'Coordinates: {latitude}, {longitude}'.format(**coord)
output:'Coordinates: 37.24N, -115.81W'

基本上,*返回元组的值,**返回字典中的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM