简体   繁体   中英

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.

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

*args will give you a variable number of arguments:

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

This also works the other way:

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

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

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

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

output : 50

String Foramtting

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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