Home > Enterprise >  MATLAB overload parentheses in a class instance
MATLAB overload parentheses in a class instance

Time:08-31

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:

  1. subsref controls () behavior.
  2. d(x) passes x to subsref, wrapped inside a struct.
  3. Unpack as x.subs{1} and do anything, including returning an output.
  4. subsref also controls {} and .; redirect these to its native implementation.
  5. 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
  • Related