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

2 ビュー (過去 30 日間)
Deepa Maheshvare
Deepa Maheshvare 2021 年 8 月 23 日
コメント済み: Deepa Maheshvare 2021 年 8 月 24 日
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 Center および File ExchangeConstruct and Work with Object Arrays についてさらに検索

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by