Initialization of class instance properties
Ältere Kommentare anzeigen
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?
Akzeptierte Antwort
Weitere Antworten (0)
Kategorien
Mehr zu Work with Components finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!