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 "", 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 "", line 1, in 
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¶

你可能感兴趣的:(Python: parameters v.s. arguments)