Class set methods that access other object properties
显示 更早的评论
Hi,
To make my question less abstract, please consider a handle class with two properties that have default values, such as age_limits=[0 150] and age=0. Also assume that age_limits needs to be dynamic; perhaps we're talking about a life insurance company that sometimes changes the minimum / maximum ages of its policy holders.
If I were to define the following set method in Matlab, I'd get a warning that "A set method for a non-Dependent property should not access another property":
function set.age(obj, age)
if age >= obj.age_limits(1) && age <= obj.age_limits(2)
obj.age = age;
end
end
This seems like completely reasonable code to me, but I'm far from an expert programmer. Is there a "better" way to set this class up?
Thanks,
Rob
回答(1 个)
Daniel Shub
2011-12-22
2 个投票
It seems reasonable. I have never really understood the reason for the warning (I think it has to do with realoading an object which has been saved to a mat file). The simpliest work around is to create an agePrivate property (which is both set and get access private). Then make age dependent and set obj.agePrivate you also need an get.age method..
类别
在 帮助中心 和 File Exchange 中查找有关 Call Python from MATLAB 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!