编写 dynamicprops
的子类允许我向对象动态添加属性:
addprop(obj, 'new_prop')
这很好,但我也很想为这些属性即时创建 set/get
函数。或对这些动态属性起作用的分析函数。
到目前为止,我对 Matlab 的体验是,一旦我创建了一个类的实例,就不可能添加新方法。这非常麻烦,因为我的对象可能包含很多数据,每次我想添加一个新方法时我都必须重新加载这些数据(因为我必须做clear classes
) .
那么有没有办法动态添加方法呢?
最佳答案
您不能像添加动态属性那样添加方法。但是,有两种方法可以在开发期间实现新方法,不需要您每次都重新加载数据。
(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')
编辑
(2.1) 下面是一个如何设置隐藏属性来存储和检索结果的示例(基于 jmlopez' answer )。显然,如果您对实际设计的内容有更好的了解,这可以得到很大改进
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
关于matlab - 是否可以向 MATLAB 类动态添加方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11862523/