How to avoid recursion in property set functions
조회 수: 8 (최근 30일)
이전 댓글 표시
I have an application where I would like to perform some additional operations when a property of a handle class is changed. For this purpose I thought I would use a property set method. Unfortunately when I do this, and the property set function uses another of the object's methods to assign the property value, I get an infinite recursion.
The documentation for property set methods states that property set methods are not called recursively, but this doesn't seem to apply if the property set method uses another of the objects methods to assign the property.https://www.mathworks.com/help/matlab/matlab_oop/property-set-methods.html
The recursion can be avoided if all of the code leading up to the property assignment, along with the property assignment are all contained just in the property set method. This can make the property set method rather bulky though.
Is there is some way to assign the property in another of the object's methods without encountering the inifinite recursion?
Also, am I misunderstanding the documentiation, regarding the set functions not being called recursively, or is this a bug?
The behavior is illustrated in the two highly simplified examples below.
In this implementation where everything is self contained in the set.a method everything works fine
h = myclassAlt
h.a = 3
But here, where the property a is assigned indirectly set.a uses the object's method assignVal to do the acutal assignment, we get an infinite recursion (until it runs out of memory)
h = myclass
h.a = 3
댓글 수: 0
채택된 답변
Matt J
2023년 10월 18일
편집: Matt J
2023년 10월 18일
The recursion can be avoided if all of the code leading up to the property assignment, along with the property assignment are all contained just in the property set method.
Or, you can offload just the code leading up to the property assignment:
classdef myclass < handle
properties
a % property to be set using set method
end
methods
function set.a(obj,val)
% set method for property a
obj.a=obj.modifyVal(val);
end
function newval=modifyVal(obj,val)
% perform the value modification
newval = min(val,5);
end
end
end
댓글 수: 5
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Function Creation에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!