Access to class properties from class methods

13 ビュー (過去 30 日間)
Metin Akyol
Metin Akyol 2022 年 2 月 2 日
編集済み: Metin Akyol 2022 年 2 月 3 日
I would like to access my classes properties from with the classes methods (both read and write access) but I am getting an 'unrecognized variable' error when doing this:
classdef class1
properties (Access = public)
var1, var2, var3
end
methods
function [returns, asset_names] = compute_holdings()
var1_test = var1 %% this seems to be incorrect
end
end
end

採用された回答

Benjamin Thompson
Benjamin Thompson 2022 年 2 月 2 日
Use the argument obj for class methods that need to act on properties or methods of an instance of the class.
function [returns, asset_names] = compute_holdings(obj)
var1_test = obj.var1;
end
  3 件のコメント
Steven Lord
Steven Lord 2022 年 2 月 3 日
If 'this' is implicitly passed into the method then this approach is not equivalent. For a non-Static method at least one of the inputs to the method must be an instance of the object, but you must accept that input explicitly. Note that Benjamin added an input argument to your method signature. If your method accepts multiple inputs, you should also be careful not to assume that the first input is always the object. If X is an instance of the mystuff class with a method doStuff, either of these calls the doStuff method in the mystuff class:
y = doStuff(X, 1)
z = doStuff(1, X) % Calling mystuff methods on the first input may error
Metin Akyol
Metin Akyol 2022 年 2 月 3 日
編集済み: Metin Akyol 2022 年 2 月 3 日
Very helpful, thank you for clarifying 'this' (no pun intended) Steven. That is very good to know!!! (alright, I'll admit it, the pun was intended ;-)).

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeConstruct and Work with Object Arrays についてさらに検索

タグ

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by