简体   繁体   中英

Named arguments: C# vs Python

Both C# and Python allow named arguments, so you can write something like: foo(bar:1) . This is great, especially in combination with optional arguments.

My question is: what are the differences between the C# and Python named arguments, if any? I'm not interested in which is the "best", but in whether there are differences and in the possible motivations behind these differences.

And if someone knows of differences with other languages' implementations of this feature (Ruby or Objective-C, maybe), that could be interesting too.

edited to make community-wiki

Python lets you "catch" unspecified named arguments into a dict, which is pretty handy

>>> def f(**kw):
...     print kw
... 
>>> f(size=3, sides=6, name="hexagon")
{'sides': 6, 'name': 'hexagon', 'size': 3}

Python not only lets you catch unspecified named arguments into a dict, but also lets you unpack a dict into arguments:

    >>> def f(alfa, beta, gamma):
    ...     print alfa, beta, gamma
    ...
    >>> f(**{'alfa': 1, 'beta': 2, 'gamma': 3})
    1 2 3

and pass them down the stream:

    >>> def g(**kwargs):
    ...     f(**kwargs)
    ...
    >>> g(**{'alfa': 1, 'beta': 2, 'gamma': 3})
    1 2 3

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