Initialization of class instance properties
이전 댓글 표시
It seems like Matlab initializes the properties of each instance of a class to the same, single value rather than evaluating the initialization expression for each instance. Why is this? It leads to very unexpected behavior from my perspective:
This works as expected in all cases:
classdef OK < handle
properties (Access=private)
mymap
end
methods
function this = OK()
this.mymap = containers.Map();
end
function add(this, key)
this.mymap(key) = true;
end
function keylist = keys(this)
keylist = this.mymap.keys;
end
end
end
The following class has crazy behavior in 2012b:
classdef WTF < handle
properties (Access=private)
mymap = containers.Map();
end
methods
function add(this, key)
this.mymap(key) = true;
end
function keylist = keys(this)
keylist = this.mymap.keys;
end
end
end
Try these commands:
x = WTF;
y = WTF;
x.keys
>> Empty cell array: 1-by-0
y.keys
>> Empty cell array: 1-by-0
x.add('foobar');
y.keys
>> 'asdf'
Huh? How did y magically get access to x's mymap? Basically, why does Matlab evaluate its property initialization expressions only once ever rather than once per instance?
채택된 답변
추가 답변 (0개)
카테고리
도움말 센터 및 File Exchange에서 Work with Components에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!