How to set class property without calling setter function
9 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(3 个)
Krishna Chaitanya Duggineni
2016-1-27
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
Krishna Chaitanya Duggineni
2016-1-29
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
2018-10-25
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 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!