是否可以动态添加方法到matlab类(面向对象编程)?

mem*_*elf 9 oop matlab class dynamic-properties

编写子类dynamicprops允许我动态地向对象添加属性:

addprop(obj, 'new_prop')
Run Code Online (Sandbox Code Playgroud)

这很棒,但我也很乐意set / get为这些属性创建功能.或者分析处理这些动态属性的函数.

到目前为止,我对Matlab的经验是,一旦我创建了一个类的实例,就不可能添加新的方法.这非常麻烦,因为我的对象可能包含大量数据,每次我想要添加新方法时都要重新加载(因为我必须这样做clear classes).

那么有没有办法即时添加方法?

Jon*_*nas 10

您无法添加类似添加动态属性的方法.但是,在开发过程中有两种实现新方法的方法,不需要每次都重新加载数据.

(1)我将标准方法编写为单独的函数,并myMethod(obj)在开发期间将它们称为.一旦我确定它们是稳定的,我就将它们的签名添加到类定义文件中 - clear classes当然,这需要一个,但它是一个很大的延迟,并且有时你可能不得不关闭Matlab.

(2)使用set/get方法,事情有点棘手.如果您正在使用dynamicprops添加新属性,您也可以指定它们的set/get方法,但是(很可能,这些方法/函数将希望接收属性的名称,以便它们知道要引用的内容):

addprop(obj,'new_prop');
prop = findprop(obj,'new_prop');
prop.SetMethod = @(obj,val)yourCustomSetMethod(obj,val,'new_prop')
Run Code Online (Sandbox Code Playgroud)

编辑

(2.1)这是一个如何设置隐藏属性来存储和检索结果的例子(基于jmlopez的答案).显然,如果您更好地了解实际设计的内容,可以对此进行大量改进

classdef myDynamicClass < dynamicprops
    properties (Hidden)
        name %# class name
        store %# structure that stores the values of the dynamic properties
    end
    methods
        function self = myDynamicClass(clsname, varargin)
            % self = myDynamicClass(clsname, propname, type)
            % here type is a handle to a basic datatype.
            self.name_ = clsname;
            for i=1:2:length(varargin)
                key = varargin{i};
                addprop(self, key);
                prop = findprop(self, key);
                prop.SetMethod = @(obj,val)myDynamicClass.setMethod(obj,val,key);
                prop.GetMethod = @(obj)myDynamicClass.getMethod(obj,key);
            end
        end
        function out = classname(self)
            out = self.name_;
        end
    end
    methods (Static, Hidden) %# you may want to put these in a separate fcn instead
        function setMethod(self,val,key)
           %# have a generic test, for example, force nonempty double
           validateattributes(val,{'double'},{'nonempty'}); %# will error if not double or if empty

           %# store
           self.store.(key) = val;

        end
        function val = getMethod(self,key)
           %# check whether the property exists already, return NaN otherwise
           %# could also use this to load from file if the data is not supposed to be loaded on construction 
           if isfield(self.store,key)
              val = self.store.(key);
           else
              val = NaN;
           end
        end
    end
end
Run Code Online (Sandbox Code Playgroud)