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

4 vues (au cours des 30 derniers jours)
Deepa Maheshvare
Deepa Maheshvare le 23 Août 2021
Commenté : Deepa Maheshvare le 24 Août 2021
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.

Réponse acceptée

Turlough Hughes
Turlough Hughes le 24 Août 2021
Modifié(e) : Turlough Hughes le 24 Août 2021
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 commentaires
Turlough Hughes
Turlough Hughes le 24 Août 2021
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 le 24 Août 2021
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

Connectez-vous pour commenter.

Plus de réponses (0)

Produits


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by