简体   繁体   中英

Python equivalent of R's … for matching function arguments

Within R, you can use a special argument ... when defining functions, which is described here :

This argument will match any arguments not otherwise matched, and can be easily passed on to other functions. This is useful if you want to collect arguments to call another function, but you don't want to prespecify their possible names.

This means that if I write a function a that uses another function b within it, I don't need to include all of the possible arguments of b as arguments to a in order to use them.

In Python, is there anything equivalent?

There's no single construct, but a combination of * and ** parameters does the same, I believe.

def g(x, y, z):
    return x + y + z

def f(x, *args, **kwargs):
    print(x)
    print(args)
    print(kwargs)
    print(g(*args, **kwargs))

f(9, 1, 2, z=3)

produces

9
(1, 2)
{'z': 3}
6

as output.

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