2

Just wondering if it is possible to use both an optional argument in the same function as multiple arguments. I've looked around and I feel as if I just have the vocabulary wrong or something. Example:

def pprint(x, sub = False, *Headers):
  pass

Can I call it still using the multiple headers without having to always put True or False in for sub? I feel like it's a no because Headers wouldn't know where it begins. I'd like to explicitly state that sub = True otherwise it defaults to False.

4

3 回答 3

6

In Python 3, use:

def pprint(x, *headers, sub=False):
    pass

putting the keyword arguments after the positionals. This syntax will not work in Python 2.

Demo:

>>> def pprint(x, *headers, sub=False):
...     print(x, headers, sub)
... 
>>> pprint('foo', 'bar', 'baz', sub=True)
foo ('bar', 'baz') True
>>> pprint('foo', 'bar', 'baz')
foo ('bar', 'baz') False

You must specify a different value for sub using a keyword argument when calling the pprint() function defined here.

于 2013-07-18T16:53:57.773 回答
0

I want to say yes because lots of matplotlib (for example) methods have something similar to this...

For example,

matplotlib.pyplot.xcorr(x, y, normed=True, detrend=<function detrend_none at 0x2523ed8>, usevlines=True, maxlags=10, hold=None, **kwargs)

When I'm using this I can specify any of the keyword arguments by saying maxlags=20 for example. You do have to specify all the non-keyworded arguments (so x in your case) before the keyword arguments.

于 2013-07-18T16:54:34.407 回答
0

Just do the following:

def pprint(x, **kwargs):
    sub = kwargs.get('sub', False)
    headers = kwargs.get('headers', [])
于 2013-07-18T16:54:56.740 回答