I am creating a class in MATLAB and while I have little experience with objects, I am almost positive I should be able to set a class property using a class method. Is this possible in MATLAB?
classdef foo
properties
changeMe
end
methods
function go()
(THIS OBJECT).changeMe = 1;
end
end
end
f = foo;
f.go;
t.change开发者_JAVA技巧Me;
ans = 1
Yes, this is possible. Note that if you create a value object, the method has to return the object in order to change a property (since value objects are passed by value). If you create a handle object (classdef foo<handle
), the object is passed by reference.
classdef foo
properties
changeMe = 0;
end
methods
function self = go(self)
self.changeMe = 1;
end
end
end
As mentioned above, the call of a setting method on a value object returns the changed object. If you want to change an object, you have to copy the output back to the object.
f = foo;
f.changeMe
ans =
0
f = f.go;
f.changeMe
ans =
1
精彩评论