Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
462 views
in Technique[技术] by (71.8m points)

function - Python: Passing parameters by name along with kwargs

In python we can do this:

def myFun1(one = '1', two = '2'):
    ...

Then we can call the function and pass the arguments by their name:

myFun1(two = 'two', one = 'one')

Also, we can do this:

def myFun2(**kwargs):
    print kwargs.get('one', 'nothing here')

myFun2(one='one')

So I was wondering if it is possible to combine both methods like:

def myFun3(name, lname, **other_info):
    ...

myFun3(lname='Someone', name='myName', city='cityName', otherInfo='blah')

In general what combinations can we do?

Thanks and sorry for my silly question.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The general idea is:

def func(arg1, arg2, ..., kwarg1=default, kwarg2=default, ..., *args, **kwargs):
    ...

You can use as many of those as you want. The * and ** will 'soak up' any remaining values not otherwise accounted for.

Positional arguments (provided without defaults) can't be given by keyword, and non-default arguments can't follow default arguments.

Note Python 3 also adds the ability to specify keyword-only arguments by having them after *:

def func(arg1, arg2, *args, kwonlyarg=default):
    ...

You can also use * alone (def func(a1, a2, *, kw=d):) which means that no arguments are captured, but anything after is keyword-only.

So, if you are in 3.x, you could produce the behaviour you want with:

def myFun3(*, name, lname, **other_info):
    ...

Which would allow calling with name and lname as keyword-only.

Note this is an unusual interface, which may be annoying to the user - I would only use it in very specific use cases.

In 2.x, you would need to manually make this by parsing **kwargs.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...