"OOP"方法调用语法与"functional"方法调用语法的区别



在这个解释inputParser类用法的页面上,

我们看到示例中每个inputParser方法调用的形式为

methodname(object, arguments)

而不是

object.methodname(arguments)

例如

addRequired(p,'filename',@ischar)

而不是

p.addRequired('filename',@ischar)

其中p是一个实例,如果inputParser .

我想说的是,这使得不清楚addRequired来自哪里,而不必在调用它之前搜索它which或在代码中搜索实例化行。在任何上下文中提供addRequired会破坏封装,并且似乎与您最初引入 OOP 时想要的完全相反。

我怀疑有充分的理由牺牲可读性并以这种特定方式编写文档。

所以我的问题是,MATLAB 中的"函数式"和"OOP"语法之间有什么实际区别吗?

怕这些语法甚至不完全等价,可以从以下示例中了解到:

>> f = fit( (1:3).', (2:2:6).' ,'poly1')
f = 
     Linear model Poly1:
     f(x) = p1*x + p2
     Coefficients (with 95% confidence bounds):
       p1 =           2  (2, 2)
       p2 =  -6.784e-16  (-4.709e-14, 4.574e-14)
>> methods(f)
Methods for class cfit:
argnames       cfit           coeffvalues    dependnames    feval          formula        integrate      numargs        plot           probnames      setoptions     
category       coeffnames     confint        differentiate  fitoptions     indepnames     islinear       numcoeffs      predint        probvalues     type           
>> f.coeffvalues
Error using cfit/subsref (line 18)
The name 'coeffvalues' is not a coefficient or a problem parameter.  You can only use dot notation to access the coefficients and problem parameters of a cfit or sfit, e.g.,
'f.p1'.
For the current fit, you can access these properties: p1, p2
You can get coefficient names and values either by name, e.g., p1 = f.p1, or by using the coeffnames or coeffvalues functions, e.g., names = coeffnames(f).
To use methods, use functional notation instead, e.g., plot(f). 
>> coeffvalues(f)
ans =
    2.0000   -0.0000

最重要的是:

要使用方法,请改用函数表示法,例如 plot(f(。

现在假设我们是虐待狂,想要自己编写一个行为类似的函数,进一步调查我们发现cfit.coeffvalues只是私有财产的获取者。现在,如果您仔细查看上面的错误,您会注意到它甚至没有发生在cfit.coeffvalues中,而是发生在cfit.subsref

总之,

中我们可以从经验上了解到,函数表示法直接进入所讨论的方法,而 OOP 表示法首先通过类的可能被覆盖的subsref方法。我想如果你想确保你跳过任何自定义subsref,使用函数符号。

最新更新