How to return the name (identifier) of the object from the call, inside a method of that class

조회 수: 7 (최근 30일)
Here is a simple example:
classdef simpleClassA
properties
prop1
end
methods
function obj = simpleClassA(x)
obj.prop1 = x;
objName = whatsMyName?
fprintf('Property prop1 of %s = %g', objName, x)
end
end
end
Then, at the command prompt, I construct an object of simpleClassA by:
Gold = simpleClassA(3.0);
and I expect this to display:
"Property prop1 of Gold = 3.0"
What function is "whatsMyName?" in my constructor method that would give me this result?
When I searched the MATLAB Answers database, the closest thing to what I want is these two links below but not exactly:

채택된 답변

Walter Roberson
Walter Roberson 2017년 12월 15일
You need the techniques described in https://www.mathworks.com/matlabcentral/answers/16693-within-a-function-get-complete-command-line-calling-text-a-la-dbstack to get the text of the executing command, and then parse it to find the variable name.
Keep in mind, though, that it is legal to have multiple statements on the same line:
set(Gold, 'prop1', 3.0); set(Silver, 'prop1', 3.0);
You might find it difficult to figure out which of the two set() you are executing.
  댓글 수: 3
Walter Roberson
Walter Roberson 2017년 12월 18일
I thought I had experimented with that and had it fail.
The difficulty with that approach is that you are trying to do this in a constructor rather than in a method after the object already exists. Your original version of the question was related to a set method(), in which case the object already exists; your edit has it happen in the constructor, and since the object does not exist yet you have to use techniques that figure out which line of code is executing and retrieve the source code of that line and figure out where you are on the source line (since there might be multiple calls to the same constructor.)
Yves
Yves 2017년 12월 20일
Thanks, @Walter. You were right; I actually don't need to know the name in the constructor, but once the constructor was called, I could use inputname(1) to capture the name of the object in any method of the class.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Construct and Work with Object Arrays에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by