【问题标题】:MATLAB - list all methods supplied by subclass only?MATLAB - 仅列出子类提供的所有方法?
【发布时间】:2012-05-29 23:28:55
【问题描述】:

我有一个继承自多个超类的类,我想获取该类具有的方法。天真地使用 methods() 从我正在使用的类中返回方法以及超类方法,但我对超类方法不感兴趣。

知道怎么做吗?我在 MATLAB 文档中找不到任何内容。

谢谢!

【问题讨论】:

  • 您使用的是新式 MCOS 类(带有 classdef 文件)还是旧式类?

标签: oop matlab


【解决方案1】:

如果您的子类没有重新实现超类的任何方法(或者如果您可以忽略重新实现的方法),您可以使用函数 METHODSSUPERCLASSES 来查找子类方法的列表也不是任何超类的方法。例如:

>> obj = 'hgsetget';  %# A sample class name
>> supClasses = superclasses(obj)

supClasses = 

    'handle'    %# Just one superclass, but what follows should handle more

>> supMethods = cellfun(@methods,supClasses,...  %# Find methods of superclasses
                        'UniformOutput',false);
>> supMethods = unique(vertcat(supMethods{:}));  %# Get a unique list of
                                                 %#   superclass methods
>> subMethods = setdiff(methods(obj),supMethods)  %# Find methods unique to the
                                                  %#   subclass
subMethods = 

    'get'
    'getdisp'
    'set'
    'setdisp'

【讨论】:

  • 我希望有一个优雅的内置函数可以做到这一点,但我有点认为这种类型的解决方案就是它的归宿。非常感谢!
【解决方案2】:

即使这个问题已经解决,让我使用meta.class 功能添加另一个答案:

%# some class name
clname = 'hgsetget';

%# obtain class meta-info
mt = meta.class.fromName(clname);

%# get name of class defining each method
cdef = arrayfun(@(c)c.Name, [mt.MethodList.DefiningClass], 'Uniform',false);

%# keep only methods that are defined in the subclass
subMethods = {mt.MethodList(ismember(cdef,clname)).Name}

这个例子的结果:

subMethods = 
    'set'    'get'    'setdisp'    'getdisp'    'empty'

注意结果如何还包括所有非抽象类都具有的静态方法empty(用于创建该类的空数组)。

【讨论】:

  • 您也可以使用类运算符'?'获取元类,如“mt = ?hgsetget”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-01
相关资源
最近更新 更多