Non è possibile aggiungere metodi come aggiungere proprietà dinamiche. Tuttavia, ci sono due modi per implementare nuovi metodi durante lo sviluppo che non richiedono di ricaricare i dati ogni volta.
(1) Scrivo i metodi standard come funzioni separate e li chiamano come myMethod(obj)
durante lo sviluppo. Una volta che sono sicuro che sono stabili, aggiungo la loro firma nel file di definizione della classe - questo richiede uno clear classes
, ovviamente, ma è molto ritardato, e di tanto in tanto potrebbe essere necessario chiudere Matlab, in ogni caso .
(2) Con i metodi set/get, le cose sono un po 'più complicate. Se si utilizza dynamicprops
per aggiungere nuove proprietà, è anche possibile specificare i loro metodi set/get, tuttavia (molto probabilmente, questi metodi/funzioni vorranno ricevere il nome della proprietà in modo che sappiano a cosa fare riferimento):
addprop(obj,'new_prop');
prop = findprop(obj,'new_prop');
prop.SetMethod = @(obj,val)yourCustomSetMethod(obj,val,'new_prop')
EDIT
(2,1) Ecco un esempio di come impostare una proprietà nascosta per archiviare e recuperare i risultati (in base a jmlopez' answer). Ovviamente questo può essere migliorato molto se si dispone di una migliore idea che cosa si sta effettivamente progettando
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
È possibile aggiungere nuovi metodi finché si eliminano le classi in seguito, ma si desidera aggirare il problema. Non penso che funzionerà in generale. –