access data returned from a method of a class in other methods
2 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Deepa Maheshvare
il 23 Ago 2021
Commentato: Deepa Maheshvare
il 24 Ago 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.
0 Commenti
Risposta accettata
Turlough Hughes
il 24 Ago 2021
Modificato: Turlough Hughes
il 24 Ago 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 Commenti
Turlough Hughes
il 24 Ago 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
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Construct and Work with Object Arrays in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!