- Property Definition, Initialize Property Values
- Evaluation of Expressions in Class Definitions, Expression Evaluation in Handle and Value Classes
Correct way to specify default property values when constructor uses inputParser.
15 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Hau Kit Yong
am 14 Apr. 2019
Bearbeitet: per isakson
am 16 Apr. 2021
As per the title, I have a class where the constructor passes a varargin input argument into inputParser, which I set up by using several addParameter commands to specify name-value pairs. I see two ways to specify default values for the object's properties:
- Assign the default values in the properties block, say Prop1 = defaultVal1, and have addParameter take in obj.Prop1 for its defaultVal input argument, i.e. use addParameter(inputParser, 'Prop1', obj.Prop1);
- Do not specify default values in the properties block, and have inputParser do the assignment, i.e. use addParameter(inputParser, 'Prop1', defaultVal1).
I noticed that method 1 does not work properly if I have properties that are handle objects where the default values are calls to a constructor, i.e. Prop1 = HandleClass1(). During object creation Prop1 never calls the constructor of HandleClass1 to build a new HandleClass1 object; it is instead assigned some existing HandleClass1 object. Method 2 works fine for this, as in it does create a new HandleClass1 object and assigns it to Prop1, but I still prefer the first option because it is the convention for specifying default property values. I would like to understand at what point in time in the object creation process do the properties get instantiated with the default values and if that has any effect on how I should specify them.
0 Kommentare
Akzeptierte Antwort
per isakson
am 14 Apr. 2019
Bearbeitet: per isakson
am 16 Apr. 2021
The default values of properties in the properties block are assigned once when the first object is created . Subsequent objects get the same values. This has important consequences when the value is an object of a handle class. One must distinguish between the underlying object and it's handle. See the descriptions in the documentation:
You are not the only one who has been puzzled by this behaviour. See Handle object as default class property value. (The current documentation is better than that refered to in this blog-post.)
I recommend that you use your Method 2 when the value is an object of a handle class. Method 1 will make the property in question of all objects refer to the same underlying "handle object".
Added later: An answer by MathWorks Support Team When I have nested objects, changing the parameter of one object changes the same parameter in others
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Argument Definitions finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!