【问题标题】:"__call__" equivalent in Matlab classdefMatlab classdef 中的“__call__”等价物
【发布时间】:2017-10-06 00:26:32
【问题描述】:

是否可以在 MATLAB 中定义类似于 Python 中的“call”方法的类方法?

您将如何在 MATLAB 中实现以下 Python 类。

class Basic(object):

    def __init__(self, basic):
        self.basic = basic

    def __call__(self, x, y):
        return (numpy.sin(y) *numpy.cos(x))

    def _calc(self, y, z):
        x = numpy.linspace(0, numpy.pi/2, 90)
        basic = self(x, y)
        return x[tuple(basic< b).index(False)]

【问题讨论】:

    标签: python matlab class object call


    【解决方案1】:

    要在 MATLAB 中创建 "callable" 的类对象,您需要修改 subsref 方法。这是当您对对象A 使用A(i)A{i}A.i 等下标索引操作时调用的方法。由于在 MATLAB 中调用函数和索引对象都使用(),因此您必须修改此方法以模仿可调用行为。具体来说,您可能希望定义 () 索引以展示 scalar obect 的可调用行为,但展示非标量对象的法线向量/矩阵索引。

    这是一个示例class(使用this documentation 来定义subsref 方法),它将其属性提升为可调用行为的幂:

    classdef Callable
    
      properties
        Prop
      end
    
      methods
    
        % Constructor
        function obj = Callable(val)
          if nargin > 0
            obj.Prop = val;
          end
        end
    
        % Subsref method, modified to make scalar objects callable
        function varargout = subsref(obj, s)
          if strcmp(s(1).type, '()')
            if (numel(obj) == 1)
              % "__call__" equivalent: raise stored value to power of input
              varargout = {obj.Prop.^s(1).subs{1}};
            else
              % Use built-in subscripted reference for vectors/matrices
              varargout = {builtin('subsref', obj, s)};
            end
          else
            error('Not a valid indexing expression');
          end
        end
    
      end
    
    end
    

    以下是一些用法示例:

    >> C = Callable(2)  % Initialize a scalar Callable object
    
    C = 
      Callable with properties:
        Prop: 2
    
    >> val = C(3)  % Invoke callable behavior
    
    val =
         8         % 2^3
    
    >> Cvec = [Callable(1) Callable(2) Callable(3)]  % Initialize a Callable vector
    
    Cvec = 
      1×3 Callable array with properties:
        Prop
    
    >> C = Cvec(3)  % Index the vector, returning a scalar object
    
    C = 
      Callable with properties:
        Prop: 3
    
    >> val = C(4)  % Invoke callable behavior
    
    val =
        81         % 3^4
    

    【讨论】:

      猜你喜欢
      • 2021-11-02
      • 2016-09-18
      • 2018-05-29
      • 2020-02-13
      • 2015-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多