classdef Dog
methods
function bark(obj, text)
disp(text)
end
end
end
Suppose d = Dog(). Is there a way to make d("woof") be same as d.bark("woof")? Can the behavior of d() be changed in any other way?
In Python, that's overloading __call__.
CodePudding user response:
- subsref controls
()behavior. d(x)passesxtosubsref, wrapped inside astruct.- Unpack as
x.subs{1}and do anything, including returning an output. subsrefalso controls{}and.; redirect these to its native implementation.- MATLAB recommends a mixin class, but that seems overkill.
Thanks to @CrisLuengo for the pointers. If anyone has more info, feel free to share.
classdef Dog
methods
function bark(obj, text)
disp(text)
end
function varargout = subsref(obj, x)
if x(1).type == "()" && length(x) == 1 && ~isempty(x.subs)
[varargout{1:nargout}] = obj.bark(x.subs{1});
else
[varargout{1:nargout}] = builtin('subsref', obj, x);
end
end
end
end
