次の解決策は、いくつかの回避策/ハックから生じたものであり、標準の MATLAB の OO 構造の一部ではありません。注意して使用してください。
必要がある:
evalin()
ワークスペース変数'caller'
の名前とクラスをワークスペースに'base'
- 最後に実行されたコマンドを取得する
- たとえば、割り当てられた変数の名前を抽出します
regexp()
- 名前とクラスを比較します。完全に一致した場合、つまり、
'base'
ワークスペース内の変数が同じクラスの新しいインスタンスで上書きされている場合は、ユーザーにinput()
. ユーザーが既存のオブジェクトを保持することを選択した場合は、新しいインスタンスを既存のインスタンスで上書きしますevalin('caller',...)
。
クラスfoo
:
classdef foo < handle
properties
check = true;
end
methods
function obj = foo()
% variable names and sizes from base workspace
ws = evalin('base','whos');
% Last executed command from window
fid = fopen([prefdir,'\history.m'],'rt');
while ~feof(fid)
lastline = fgetl(fid);
end
fclose(fid);
% Compare names and classes
outname = regexp(lastline,'\<[a-zA-Z]\w*(?=.*?=)','match','once');
if isempty(outname); outname = 'ans'; end
% Check if variables in the workspace have same name
idx = strcmp({ws.name}, outname);
% Ask questions
if any(idx) && strcmp(ws(idx).class, 'foo')
s = input(sprintf(['''%s'' already exists. '...
'Replace it with default? (y/n): '],outname),'s');
% Overwrite new instance with existing one to preserve it
if strcmpi(s,'n')
obj = evalin('caller',outname);
end
end
end
end
end
活動中のクラス:
% create class and change a property from default (true) to false
clear b
b = foo
b =
foo with properties:
check: 1
b.check = false
b =
foo with properties:
check: 0
% Avoid overwriting
b = foo
'b' already exists. Replace it with default? (y/n): n
b
b =
foo with properties:
check: 0
弱点(上記のポイントを参照):
- cmw 行とスクリプトで実行されるコマンドにのみ適用され、関数には適用されません (関数呼び出しに拡張するためのリンクを参照してください)。また、 history.mの読み取りで問題が発生した場合に壊れる可能性があります。
- 現在の正規表現は で失敗し
a==b
ます。
- ユーザー入力
evalin()
が潜在的なセキュリティ上の脅威にさらされるため、危険です。入力が正規表現と文字列比較でフィルター処理されたとしても、コードが後で再検討されると、構造が問題を引き起こす可能性があります。