Matlab类在构造函数中具有实例名称的知识 [英] Matlab class with knowledge of instance name in the constructor

查看:168
本文介绍了Matlab类在构造函数中具有实例名称的知识的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想拥有一个在其构造函数中可以知道其实例名称(以字符串形式提取)的类.

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

这需要丑陋的

A = mysession;  A.build

语法才能正常工作...

syntax in order to work...

推荐答案

无法获取用于分配函数或类构造函数输出的变量名称.如您所见,在调用工作空间中获取对象变量名的唯一方法是调用该类的另一种方法,此时您可以使用inputname进行查询.

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.

此外,尚不清楚您为什么需要执行此操作,但我强烈建议不要这样做.特别是对于handle类,您可以有多个变量指向 same 对象,因此,该对象在技术上具有多个名称.

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.

这篇关于Matlab类在构造函数中具有实例名称的知识的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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