필터 지우기
필터 지우기

access data returned from a method of a class in other methods

조회 수: 4 (최근 30일)
I've the following class
classdef setting
SETTING Summary of this class goes here
Detailed explanation goes here
properties(Constant)
n = setting.get_n;
q = setting.get_q;
end
methods(Static)
function data = load_setting
File = 'Configuration.ini';
I = INI('File',File);
I.read();
data = I.get('UserData'); % struct
end
function n = get_n
data = setting.load_setting;
n = data.m + 2;
end
function q = get_q
data = setting.load_setting;
temp = data.q;
q = fieldnames(temp);
end
end
end
I'd like to know if it is possible to access `data` returned by load_setting automatically in the rest of the methods defined in the class instead of calling it `data = load_setting ` in each method. Suggestions will be really helpful.

채택된 답변

Turlough Hughes
Turlough Hughes 2021년 8월 24일
편집: Turlough Hughes 2021년 8월 24일
You could make it a private property, the private property can only be accessed by the class (see property attributes). You're probably also best to initialise obj.data in the constructor; this means you wont have to invoke the function obj.setting, data is created when the object is instatiated:
classdef setting
properties (Access = private)
data
end
methods
function obj = setting %rename load_setting to setting to make it a constructor
obj.data = 'someData';
end
function test(obj)
obj.data
end
end
end
Calling obj.test, demonstrates that you can access the data property, obj.data, anywhere inside your class:
s = setting
s.test
ans =
'someData'
  댓글 수: 2
Turlough Hughes
Turlough Hughes 2021년 8월 24일
You could also keep the load_setting function and call that from the constructor this way:
classdef setting
properties (Access = private)
data
end
methods
function obj = setting % constructor
obj = load_setting(obj);
end
function obj = load_setting(obj)
obj.data = 'someData';
end
function test(obj)
obj.data
end
end
end
Deepa Maheshvare
Deepa Maheshvare 2021년 8월 24일
Thanks for the reposne. Could you please clarify the following
When data is a struct how should I access data to set up constant properties defined in the method `get_n` and `get_q` mentioned in my original post?
properties(Constant)
n = setting.get_n;
q = setting.get_q;
end

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Whos에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by