简体   繁体   中英

Convert varargin and nargin to from Matlab to Python

How would one convert the following Matlab code to Python? Are there equivalent functions to Matlab's varargin and nargin in Python?

function obj = Con(varargin)

    if nargin == 0
        return
    end

    numNodes = length(varargin);
    obj.node = craft.empty();
    obj.node(numNodes,1) = craft();

    for n = 1:numNodes                
        % isa(obj,ClassName) returns true if obj is an instance of 
        % the class specified by ClassName, and false otherwise. 

        % varargin is an input variable in a function definition 
        % statement that enables the function to accept any number 
        % of input arguments.

        if isa(varargin{n},'craft')
            obj.node(n) = varargin{n};
        else
            error(Invalid input for nodes property.');
        end
    end
end

varargin 's equivalent

The *args and **kwargs is a common idiom to allow arbitrary number of arguments to functions. The single asterisk form ( *args ) is used to pass a non-keyworded , variable-length argument list, and the double asterisk ( **kwargs ) form is used to pass a keyworded , variable-length argument list.

Here is an example of how to use the non-keyworded form:

>>> def test_args(*args):
...     # args is a tuple
...     for a in args:
...         print(a)
...
>>> test_args(1, 'two', 3)
1
two
3

Here is an example of how to use the keyworded form:

>>> def test_kwargs(**kwargs):
...     # kwargs is a dictionary
...     for k, v in kwargs.items():
...         print('{}: {}'.format(k, v))
...
>>> test_kwargs(foo = 'Hello', bar = 'World')
foo: Hello
bar: World

nargin 's equivalent

Since nargin is just the number of function input arguments ( ie , number of mandatory argument + number of optional arguments), you can emulate it with len(args) or len(kwargs) .

def foo(x1, x2, *args):
    varargin = args
    nargin = 2 + len(varargin) # 2 mandatory arguments (x1 and x2) 
    # ...

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