我想要一个我可以访问的只读字段fv=object.field
,但返回的值是从对象的其他字段计算的(即返回值满足fv==f(object.field2)
)。
所需的功能与property
Python 中的函数/装饰器相同。
我记得看到一个参考,这可以通过设置properties
块的参数来实现,但是 Matlab OOP 文档太分散了,我再也找不到了。
这称为“从属”属性。下面是一个使用派生属性的类的快速示例:
classdef dependent_properties_example < handle %Note: Deriving from handle is not required for this example. It's just how I always use classes.
properties (Dependent = true, SetAccess = private)
derivedProp
end
properties (SetAccess = public, GetAccess = public)
normalProp1 = 0;
normalProp2 = 0;
end
methods
function out = get.derivedProp(self)
out = self.normalProp1 + self.normalProp2;
end
end
end
定义了这个类后,我们现在可以运行:
>> x = dependent_properties_example;
>> x.normalProp1 = 3;
>> x.normalProp2 = 10;
>> x
x =
dependent_properties_example handle
Properties:
derivedProp: 13
normalProp1: 3
normalProp2: 10
You can use the property access methods: http://www.mathworks.co.uk/help/matlab/matlab_oop/property-access-methods.html
To define get/set functions - the get function should allow you to return values computed from other members. The section "When to Use Set Methods with Dependent Properties" in the link above gives an example for this.