Using function handles with private properties and private methods
古いコメントを表示
Hello, everyone. I have been experimenting with the use of function handles on classes with private methods and/or have private properties. I have provided a simple example class below. I am currently using Matlab R2023a, but I also got the same results using Matlab R2019b.
classdef test % < handle
properties (Access = private)
this
that
testVar
end
properties (Access = private)
fn
end
methods (Access = public)
function obj = test( accessSwitch )
obj.this = 'This';
obj.that = 'That';
obj.testVar = 2;
if ( accessSwitch )
obj.fn = @obj.takeThat;
obj.testVar = 1;
obj.that = '123';
elseif (~accessSwitch)
obj.fn = @obj.considerThis;
obj.testVar = 2;
obj.this = '456';
else
error('not hitting the above cases');
end
end
function processTest(testObj)
testObj.fn();
end
end
methods (Access = private)
function takeThat( obj )
fprintf( '%s\n', obj.that );
end
function considerThis( obj )
fprintf( '%s\n', obj.this );
end
end
end
I tested this class with the accessSwitch set both to 0 and 1. I set a breakpoint in the debugger at the point where the "takeThat" or "considerThis" function is called. In both cases, the private properties are not updated. "testVar" remains as 2, even if the accessSwitch is 1. Additionally, the "that" and "this" properties are not modified to "123" or "456" either. It appears that when the function handle is defined, it saves the current values of the properties and does not account for further modifications of the properties.
Correct me if I am mistaken, but creating a function handle shouldn't restrict any further modifications to the values of the private properties, correct? I continued to experiment and noticed that creating the function handle after changing the property values instead results in "testVar" and "that" using "1" and "123" respectively when calling the "processTest" function (see code block below). This is the result I would have expected from the original implementation above.
if ( accessSwitch )
obj.testVar = 1;
obj.that = '123';
obj.fn = @obj.takeThat;
Is this importance of where you create your function handle intentional? If so, why?
Lastly, I am aware that uncommenting the section in the classdef line (i.e., making it a handle class) effectively prevents the problem. However, I would prefer not to define a handle class, as the ability to assign a handle object to multiple variables can be dangerous. I would like to mitigate this risk.
Thank you for your help.
.
採用された回答
その他の回答 (0 件)
カテゴリ
ヘルプ センター および File Exchange で Function Handles についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!