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 equivalentThe *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 equivalentSince nargin
is just the number of function input arguments (i.e., 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)
# ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With