在MATLAB中,是否有可能在创建一个对象之前检查一个对象是否已经存在? [英] In MATLAB, is it possible to check if an object already exists before creating a new one?

查看:2270
本文介绍了在MATLAB中,是否有可能在创建一个对象之前检查一个对象是否已经存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何询问用户是否要使用默认对象替换同一类的上一个对象,或者在调用构造函数时直接使用上一个对象。

I'm trying to figure out how to ask the user whether they want to replace the previous object of the same class with the default object, or simply use the previous object, when calling the constructor.

我在这两种情况下都在寻找动作:

I'm looking for actions in both these cases:

>>obj = Obj()
'obj' already exists. Replace it with default? (y/n): y
%clear obj and call default constructor to create new obj

>>obj = Obj()
'obj' already exists. Replace it with default? (y/n): n
%cancel call of Obj()

做这个?我已经搞砸了默认构造函数,没有效果。

How would I do this? I've messed around with the default constructor, to no avail.

编辑:如果它有什么区别,Obj是Handle的子类。

If it makes any difference, Obj is a subclass of Handle.

推荐答案

以下解决方案源于几种解决方法/ hacks,不是标准MATLAB的OO结构的一部分。

The following solution stems from several workarounds/hacks and is not part of the standard MATLAB's OO constructs. Use with caution.

您需要:


    <在'调用者工作区中的'的名称和类的
  1. evalin()工作区变量

  2. 检索最后执行的命令

  3. 使用eg提取所分配变量的名称 regexp()

  4. 比较名称和类别。如果发生总匹配,即'base'工作空间中的变量正被同一类的新实例覆盖,请向用户询问 input()。如果用户选择保留现有对象,则通过 evalin('caller',...)用现有对象覆盖新实例。

  1. evalin() into the 'caller' workspace the names and classes of the 'base' workpsace variables
  2. retrieve the last executed command
  3. extract the name of the assigned variable with e.g. regexp()
  4. compare names and classes. If a total match occurs, i.e. the variable in the 'base' workspace is being overwritten with a new instance of the same class, ask the user for input(). If the user chooses to preserve the existing object, overwrite the new instance with the existing one through 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


$ b b

动作类:

Class in action:

% 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

弱点(见上述):


  1. 仅适用于cmw行和脚本执行的命令,而不是函数(请参阅扩展到函数调用的链接)。

  2. 当前正则表达式在 a == b

  3. 危险,因为 evalin() 2794016 />用户输入将打开潜在的安全威胁。即使输入使用正则表达式和字符串比较过滤,如果稍后再次查看代码,则构造可能会出现问题。

  1. applies only to cmw line and script executed commands, not functions (see link to extend to function calls). Also, might break in case of problems reading history.m.
  2. the current regex fails on a==b.
  3. Dangerous because the evalin() on user input leaves potential security threats open. Even if the input is filtered with the regexp and the string comparison, the construct might pose a problem if the code is revisited later on.

这篇关于在MATLAB中,是否有可能在创建一个对象之前检查一个对象是否已经存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆