Main Content

UnderstandPythonFunction Arguments

Your Python®documentation shows you how to call a Python function. Python function signatures look similar to MATLAB®function signatures. However, Python has syntax which might be unfamiliar to MATLAB users.

位置参数

Apositionalargument is passed by position. These arguments appear at the beginning of a function signature.

Python Signature MATLAB Usage

abs(X)
ArgumentXis required.

>> py.abs(-99)

Some functions accept an arbitrary sequence of positional arguments, including no arguments. In Python, these arguments are defined by prepending the name with the*character.

Python Signature MATLAB Usage

itertools.izip(*iterables)
Theiterablesargument is not required, in which case, the function returns a zero length iterator.

Aggregate elements from two lists.
>> py.itertools.izip(... py.list({1:10}),py.list({'a','b'}));


Create zero length iterator.
>> py.itertools.izip;

print(*objects)

>> words = {'Hello','World!'};
>> py.print(words{:})

Keyword Arguments

Akeywordargument is preceded by an identifier. Keyword arguments, also callednamedarguments, can be specified in any order. Keyword arguments are like name-value pairs in MATLAB. Use the MATLABpyargsfunction to create keyword arguments for Python functions.

Python Signature MATLAB Usage

print(*objects,sep='',end='\n',
file=sys.stdout)

sep,end, andfileare keyword arguments.

Change the value ofend.
>> py.print('string',pyargs('end','--'))

This example uses the default value for thefilekeyword. Create some text variables.

x1 = py.str('c:'); x2 = py.os.curdir; x3 = py.os.getenv('foo'); py.print(x1,x2,x3)
c: . None

To display the values on separate lines, use newline,\n, as a separator.

py.print(x1,x2,x3,pyargs('sep',sprintf('\n')))
c: . None

To changesepto an empty string and change theendvalue to displayTHE END, type:

py.print(x1,x2,x3,pyargs('end', sprintf(' THE END\n'),'sep',py.str))
c:.None THE END

Arbitrary Number of Keyword Arguments

Python defines an arbitrary number of keyword arguments by prepending the name with**characters.

Python Signature MATLAB Usage

dict(**kwarg)

>> D = py.dict(Joe=100,Jack=101)

Optional Arguments

Anoptionalargument is a non-required argument.

Python Signature MATLAB Usage

random.randrange(start,stop[,step])
Argumentstepis optional.

>> py.random.randrange(1,100)

Optional arguments can have default values. A default value is indicated by an equal sign=with the default value.

Python Signature MATLAB Usage

print(*objects,sep='',end='\n',
file=sys.stdout)

The default value forfileissys.stdout.

Print two values using default keyword values.
>> py.print(2,'2')

See Also