Python: parameters v.s. arguments

Parameters

A named entity in a function (or method) definition that specifies an argument (or in some cases, arguments) that the function can accept.

  • positional-or-keyword
    specifies an argument that can be passed either positionally or as a keyword argument.

for example foo and bar in the following:

def func(foo, bar=None): ...
  • keyword-only
    specifies an argument that can be supplied only by keyword.

Keyword-only parameters can be defined by including a single var-positional parameter(says args) or bare * in the parameter list of the function definition before them.

for example kw_only1 and kw_only2 in the following:

def func(arg, *, kw_only1, kw_only2): ...
  • var-positional
    specifies that an arbitrary sequence of positional arguments can be provided

Such a parameter can be defined by prepending the parameter name with *. If the form *identifier is present, it is initialized to a tuple receiving any excess positional parameters, defaulting to the empty tuple. So args is a tuple.

for example args in the following:

def func(*args, **kwargs): ...
  • var-keyword
    specifies that arbitrarily many keyword arguments can be provided

Such a parameter can be defined by prepending the parameter name with **. If the form **identifier is present, it is initialized to a new ordered mapping receiving any excess keyword arguments, defaulting to a new empty mapping of the same type. Sokwargs is a dict.

for example kwargs in the following.

def func(*args, **kwargs): ...
  • !Note: the order of parameters in the function:
def func(a, b=2, *args, **kwargs).

arguments

A value passed to a function (or method) when calling the function.

There are two kinds of argument:

  • keyword argument:
    an argument preceded by an identifier (e.g. name=) in a function call or passed as a value in a dictionary preceded by **.

For example, 3 and 5 are both keyword arguments in the following calls to complex():

complex(real=3, imag=5)
complex(**{'real': 3, 'imag': 5})
  • positional argument
    an argument that is not a keyword argument. Positional arguments can appear at the beginning of an argument list and/or be passed as elements of an iterable preceded by *.

For example, 3 and 5 are both positional arguments in the following calls:

complex(3, 5)
complex(*(3, 5))

1, What is the difference between arguments and parameters?

Parameters are defined by the names that appear in a function definition, whereas arguments are the values actually passed to a function when calling it. Parameters define what types of arguments a function can accept.

  • for example,
def func(foo, bar=None, **kwargs):
    pass

foo, bar and kwargs are parameters of func.

func(42, bar=314, extra=somevar)

However, when calling func, the values 42, 314, and somevar are arguments.

function

A function definition defines a user-defined function object.The function definition does not execute the function body; this gets executed only when the function is called.

default parameters

  • If a parameter has a default value, all following parameters up until the * must also have a default value.
>>> def foo(a, b=1, c):
...   pass
... 
  File "<stdin>", line 1
SyntaxError: non-default argument follows default argument
  • Default parameter values are evaluated from left to right when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that the same “pre-computed” value is used for each call.
>>> def foo(b=[]):
...   b.append('hello')
...   return b
... 
>>> foo()
['hello']
>>> foo()
['hello', 'hello']

A way around this is to use None as the default, and explicitly test for it in the body of the function

>>> def foo(b=None):
...   if b == None:
...     b = []
...   b.append('hello')
...   return b
... 
>>> foo()
['hello']
>>> foo()
['hello']

Functions are first-class objects.

Here's what Guido says about first class objects in his blog:

One of my goals for Python was to make it so that all objects were first class. By this, I meant that I wanted all objects that could be named in the language (e.g., integers, strings, functions, classes, modules, methods, etc.) to have equal status. That is, they can be assigned to variables, placed in lists, stored in dictionaries, passed as arguments, and so forth.

Calls

A call calls a callable object (e.g., a function) with a possibly empty series of arguments.

  • All argument expressions are evaluated before the call is attempted.

    • First, a list of unfilled slots is created for the formal parameters. If there are N positional arguments, they are placed in the first N slots.
    • Next, for each keyword argument, the identifier is used to determine the corresponding slot (if the identifier is the same as the first formal parameter name, the first slot is used, and so on). If the slot is already filled, a TypeError exception is raised. Otherwise, the value of the argument is placed in the slot, filling it (even if the expression is None, it fills the slot).
    • When all arguments have been processed, the slots that are still unfilled are filled with the corresponding default value from the function definition. (Default values are calculated, once, when the function is defined; thus, a mutable object such as a list or dictionary used as default value will be shared by all calls that don’t specify an argument value for the corresponding slot; this should usually be avoided.) If there are any unfilled slots for which no default value is specified, a TypeError exception is raised. Otherwise, the list of filled slots is used as the argument list for the call.

If keyword arguments are present, they are first converted to positional arguments, as follows.

  • If the syntax *expression appears in the function call, expression must evaluate to an iterable. Elements from these iterables are treated as if they were additional positional arguments. For the call f(x1, x2, *y, x3, x4), if y evaluates to a sequence y1, …, yM, this is equivalent to a call with M+4 positional arguments x1, x2, y1, …, yM, x3, x4.

A consequence of this is that although the *expression syntax may appear after explicit keyword arguments, it is processed before the keyword arguments (and any **expression arguments)

>>> def foo(a,b):
...   print(a,b)
... 
>>> foo(b=1, *(2,))
2 1
>>> foo(a=1, *(2,))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: foo() got multiple values for argument 'a'
>>> foo(1, *(2,))
1 2
  • If the syntax **expression appears in the function call, expression must evaluate to a mapping, the contents of which are treated as additional keyword arguments. If a keyword is already present (as an explicit keyword argument, or from another unpacking), a TypeError exception is raised.
  • A call always returns some value, possibly None, unless it raises an exception. How this value is computed depends on the type of the callable object.
    If it is—
    • a user-defined function: The code block for the function is executed, passing it the argument list. The first thing the code block will do is bind the formal parameters to the arguments. When the code block executes a return statement, this specifies the return value of the function call.

    • a built-in function or method: The result is up to the interpreter.

    • a class object: A new instance of that class is returned.

    • a class instance method: The corresponding user-defined function is called, with an argument list that is one longer than the argument list of the call: the instance becomes the first argument.

    • a class instance: The class must define a __call__() method; the effect is then the same as if that method was called.

read more

  • Calls

  • Function definitions

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,590评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 86,808评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,151评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,779评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,773评论 5 367
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,656评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,022评论 3 398
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,678评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 41,038评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,659评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,756评论 1 330
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,411评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,005评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,973评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,203评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,053评论 2 350
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,495评论 2 343

推荐阅读更多精彩内容