为什么属性不从类方法接受一个新的值? [英] why do properties not take on a new value from class method?
问题描述
我想更多地了解Matlab类及其属性。这是我创建的测试类:
classdef Test
properties
%网络类型的属性
some_var
end
方法
函数N = Test()
end
function change_var(N,val)
N.some_var = val;
end
end
end
现在, ,并调用change_var()...
> a =测试;
>> a.change_var(2);
>> a.some_var
ans =
[]
为什么属性some_var不在赋值中的值val上?
$ c> Test 类已定义为价值类到句柄类。有效地,当调用 a.change_var
时,按$值传递 a
。要将更改存储到 some_var
属性,请执行以下操作:
>> a =测试;
>> a = a.change_var(2);
另一种方法是使 Test
一个句柄类,你的问题会按照你的预期工作。为此,通过将类定义的第一行改为:
<$ p $类继承
句柄
p> classdef Test< handle
I am trying to understand a little bit more about Matlab classes and their properties. Here is a test class I have created:
classdef Test
properties
% Properties of the network type
some_var
end
methods
function N = Test()
end
function change_var( N, val )
N.some_var=val;
end
end
end
Now, I create an instance of this class, and call "change_var()"...
>> a=Test;
>> a.change_var(2);
>> a.some_var
ans =
[]
Why has the property "some_var" not taken on the value "val" in the assignment?
The Test
class has been defined as a value-class as opposed to a handle class. Effectively, when you call a.change_var
, a
is passed in by-value. To store the change to the some_var
property do this:
>> a = Test; >> a = a.change_var(2);
The alternative is to make Test
a handle class in which case the example in your question would work as you expected. To do this, inherit from the handle
class by changing the first line of your class definition to this:
classdef Test < handle
这篇关于为什么属性不从类方法接受一个新的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!