How to set class property without calling setter function
8 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
I'm looking to achieve the following code structure in my class definition for several different properties to make an instrument driver.
function set.prop(obj, value)
'send command to instrument'
obj.prop = value
end
function value = get.prop(obj)
value = obj.prop
end
funciton readprop(obj)
obj.prop = 'function to read value from instrument'
end
With this code format I can store the value in property and recall it by obj.prop without having to reread the instrument each time. However, when I call obj.readprop, this method calls the setter method. How do I get around this in the simplest way?
0 Commenti
Risposte (3)
Krishna Chaitanya Duggineni
il 27 Gen 2016
Let me know if my understanding of your question is incorrect.
'readprop' member function of a class is used to read a property from the instrument and then calls 'setter' to set the property value with the current reading. You would like to avoid calling the setter.
This requirement needs you to modify your code for 'readprop' function. For 'readprop' not to call setter function, you can add another boolean argument (ex: "enable") which is by default 1. Manipulate 'readprop' to call the 'setter' only if this argument is true(or the vice versa of this).
Member function 'readprop' will look like this
function readprop(obj,enable)
if nargin < 2
enable = true;
%get property value from instrument
end
if(enable)
%call setter
else
% Do not call setter
end
end
1 Commento
Krishna Chaitanya Duggineni
il 29 Gen 2016
Getters must have only one argument. So, passing 'enable' as an input and getting 'value' as output might be a trouble. Moreover, It will be better if the getter does not alter the value of property.
grajcjan
il 25 Ott 2018
Hi, I'm trying to solve a similar problem with set and get. Do you know how I can do something similar, using only get & set function? When I'm connected to a device, I want to read the set values directly from the device, but when I'm disconnected, I want to see the last set value and if I reconnect, I would like to set the device to the last set value.
function set.Prop(visaObject, Prop)
if strcmp(visaObject.Status,'open')
fprintf(visaObject, ['command',Prop]);
end
visaObject.Prop = Prop;
end
function Prop = get.Prop(visaObject)
if strcmp(visaObject.Status,'closed')
Prop = visaObject.Prop;
else
Prop = query(visaObject,’command’);
visaObject.Prop = Prop;
end
end
0 Commenti
Vedere anche
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!