Setting object properties without returning the object using obj = obj.myfun(obj,argin)

6 ビュー (過去 30 日間)
Hello all,
I have a syntax question. I want to be able to set or add to properties of a custom class, but without using the cumbersome "obj = setPar1(obj,argin)" syntax, where the method setPar1 is some function that determines my object's new properties based on the current properties, and argin.
Here is a clear working example of what I mean:
p = inputParser();
addParameter(p,'par1',[])
addOptional(p,'par2',[],@ischar)
parse(p,varargin{:})
Really, this is three different examples. I am modifying my object p (an inputParser) by adding optional parameters, defaults, and validation functions. Then I am applying the method parse to p, using varargin{:} as the optional input. All of these modify the internal properties of p. This is all done without using something like
p = addParameter(p,'par1',[]);
Ideally, I want something closer to:
p.addParameter('par1',[]);
but would be fine with the above working example. How do I do this?
  2 件のコメント
D. Plotnick
D. Plotnick 2018 年 11 月 14 日
Note, I thought that the inputParser might actually be a handle class, rather than a _value_ object. I could see the above working if p was actually the input parser handle. As far as I can tell, this is not how the inputParser class functions (ishandle(p) returns false).
Guillaume
Guillaume 2018 年 11 月 14 日
ishandle does not check if a variable is an instance of a handle class. It checks if the object is a graphic or java handle.
To check if a class is a handle class:
>> superclasses('inputParser')
Superclasses for class inputParser:
matlab.mixin.Copyable
handle
It is a handle class.

サインインしてコメントする。

採用された回答

Guillaume
Guillaume 2018 年 11 月 14 日
What you want is a handle class. See Comparison of Handle and Value Classes for more details.
Note that if you're not proficient with matlab and just a beginner with OOP, I wouldn't recommend you start writing handle classes until you've mastered value classes. Handle classes should be the exception rather than the norm in matlab.
  1 件のコメント
D. Plotnick
D. Plotnick 2018 年 11 月 14 日
Thanks, I brain-farted on ishandle.
No, I try to stay away from handle class objects unless I am doing UI work. Thanks again.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeArgument Definitions についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by