Matlab class with knowledge of instance name in the constructor

妖精的绣舞 提交于 2019-12-10 10:49:45

问题


I would like to have a class which, in its constructor, can have knowledge (extract as a string) its instance name.

For the moment I worked the name extraction out like this:

classdef mysession

methods (Access = public)

  function this=mysession (varargin)
    this.cargs=varargin;
    this.built=false;
  end

  function id=build(this)
    id=this.mynameis;
    this.id = id;
    %% instructions needing id 
    built=true;
  end

  function name = mynameis (this)
    name=evalin ('caller', 'inputname');
  end
end

properties  (Access=private)
    id
    built
    cargs
end
end

which requires the ugly

A = mysession;  A.build

syntax in order to work...


回答1:


There is no way to get the variable name that is used to assign the output of a function or class constructor. As you've discovered, the only way to get the object's variable name in the calling workspace is to call another method of the class at which point you can use inputname to query it.

That aside, it's not clear why you need to do this but I'd strongly discourage it. Particularly with handle classes, you can have multiple variables point to the same object, therefore the object technically has multiple names.



来源:https://stackoverflow.com/questions/39793694/matlab-class-with-knowledge-of-instance-name-in-the-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!