【问题标题】:Is it possible to change method function handlers in MATLAB classdef是否可以在 MATLAB classdef 中更改方法函数处理程序
【发布时间】:2016-12-05 03:40:03
【问题描述】:

我正在尝试使用 MATLAB OOP。我想更改类构造函数中的类方法处理程序。 例如,我有一个类test,其中类方法使用取决于类属性中的变量number 的方法之一:

mytest = test(2);
mytest.somemethod();

classdef test < handle
  properties
    number
  end
  methods        
    function obj = test(number)
      obj.number = number;
    end
    function obj = somemethod(obj)
      switch obj.number
        case 1
          obj.somemethod1();
        case 2
          obj.somemethod2();
        case 3
          obj.somemethod3();
      end
    end
    function obj = somemethod1(obj)
      fprintf('1')
    end
    function obj = somemethod2(obj)
      fprintf('2')
    end
    function obj = somemethod3(obj)
      fprintf('3')
    end
  end
end

这里每当调用test.somemethod() 时都会使用switch 运算符。 switch可以只在类构造函数初始化的时候使用一次吗(即更改方法处理程序)如下:

classdef test < handle
  properties
    number
    somemethod %<--
  end
  methods
    % function obj = somemethod(obj,number) % my mistake: I meant the constructor
    function obj = test(number)
      obj.number = number;
      switch number
        case 1
          obj.somemethod = @(obj) obj.somemethod1(obj);
        case 2
          obj.somemethod = @(obj) obj.somemethod2(obj);
        case 3
          obj.somemethod = @(obj) obj.somemethod3(obj);
      end
    end
    function obj = somemethod1(obj)
      fprintf('1')
    end
    function obj = somemethod2(obj)
      fprintf('2')
    end
    function obj = somemethod3(obj)
      fprintf('3')
    end
  end
end

test 类的第二个实现不起作用。 对于S = test(2); S.somemethod(),有一个错误: 使用测试出错>@(obj)obj.somemethod2(obj) (line ...) 输入参数不足。 怎么了?

【问题讨论】:

    标签: matlab


    【解决方案1】:

    首先,您不能将somemethod 作为方法作为属性。您可以摆脱该方法并为构造函数中的属性分配一个函数句柄。

    function self = test(number)
        self.number = number;
        switch self.number
            case 1
                self.somemethod = @(obj)somemethod1(obj)
        %....
        end
    end
    

    此外,您当前的匿名函数已将对象的 两个 副本传递给方法:

    1. obj.method 隐式传递 obj 作为第一个输入
    2. obj.method(obj) 传递 obj 的第二个副本作为第二个输入

    您希望将您的对象句柄更新为如下内容,这会将obj 的单个副本传递给该方法。

    obj.somemethod = @obj.somemethod3
    

    另外,在使用你的类时,你必须使用点符号来执行somemethod,因为它是一个属性而不是一个“真正的”方法

    S = test()
    S.somemethod()
    

    【讨论】:

    • 关于属性和方法中的相同名称是我的类型错误(我的意思是在构造函数中初始化)。但是'S = test(2); S.somemethod()' 生成错误:“Error using test>@(obj)obj.somemethod2(obj) 输入参数不足。”
    • @AlexanderKorovin 抱歉,我打错了。现在应该可以工作了
    • 谢谢!不幸的是,我发现这个实现(obj.somemethod = @ obj.somemethod3)比使用switch时慢了大约两倍!
    猜你喜欢
    • 1970-01-01
    • 2014-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-20
    • 1970-01-01
    相关资源
    最近更新 更多