Accessing properties in a class
조회 수: 7 (최근 30일)
이전 댓글 표시
I am trying to figure out if there is a way to set the value of variables defined in `classname` by calling the methods defined in it via the main function. I am passing input arguments to class from main function and after that from the terinal when I do , I don't see the values assigned to properties in the output.
classdef classname
properties
PropName
propname2
end
methods(Static)
function obj = fun1(arg1,arg2)
obj.PropName = arg1;
obj.propname2 = arg2;
end
end
end
function main(arg)
classname.fun1(arg,arg)
end
After calling classname from main, I try accessing the properties in it .
a=classname
returns
a =
classname with properties:
PropName: []
propname2: []
I expected it to return
classname with properties:
PropName: 10
propname2: 10
댓글 수: 0
답변 (2개)
Jakeb Chouinard
2021년 8월 3일
편집: Jakeb Chouinard
2021년 8월 3일
Since static methods refer to the class as a whole rather than its instances, I don't believe you would be able to set properties using a static method. This is partially because you're calling obj in the function, but in application, this obj doesn't exist as an instance of the calss, so its properties, or that of the class, can't be set by this method. My suggestion would be to set these values using their constructor function or to have them stored as constants within the class that can be overwritten:
classdef classname
properties
PropName = 10;
PropName2 = 10;
end
methods
function obj = changeProps(newArg1, newArg2)
obj.PropName = newArg1;
obj.PropName2 = newArg2;
end
end
end
*Note: Initial property values in class declaration (the ones set under properties above) cannot be variables
Or:
classdef classname
properties
PropName;
PropName2;
end
methods
function obj = classname(arg1, arg2)
obj.PropName = arg1;
obj.PropName2 = arg2;
end
function obj = changeProps(nArg1, nAarg2)
obj.PropName = nArg1;
obj.PropName2 = nArg2;
end
end
end
*nArg is short for new argument
Cheers,
Jakeb
댓글 수: 0
per isakson
2021년 8월 3일
편집: per isakson
2021년 8월 3일
There is nothing special with the name obj, it's just a name. The assignments in the method, fun1, creates a structure (named obj ) with two fields.
I assume that you tried a static method to make the one-liner, classname.fun1(arg,arg), possible.
classname_2 illustrates how to do it with an ordinary method. That requires two lines.
classname_3 illustrates a trick that makes the one-liner possible. However, DON'T USE IT. I'm convinced it will eventually cause trouble. I included it to show that the class instance, obj, must be created before it's used. If it isn't passed to the method, it can be created locally (it seems).
classname.fun1( 1, 2 )
%
a2 = classname_2;
a2.fun1( 3, 4 )
%
classname_3.fun1( 5, 6 )
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!