access data returned from a method of a class in other methods
조회 수: 2 (최근 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.
댓글 수: 0
채택된 답변
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
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
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File 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!