导入类后,通过索引对静态方法进行调用 [英] Following calls to static methods with indexing when importing classes

查看:123
本文介绍了导入类后,通过索引对静态方法进行调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在路径中的程序包文件夹+myPack中有一个类文件myClass.m.类文件的一个简单示例是:

I have a class file myClass.m in a package folder +myPack that's on the path. A simple example of the class file is:

classdef myClass
    properties
        prop
    end

    methods
        function obj = myClass(x)
            obj.prop = x;
        end
    end
end 

现在,如果我直接调用该方法并使用完整的包名称访问属性,即:

Now if I directly call the method and access the property using the full package name, i.e.:

x = myPack.myClass(2).prop;

正确返回x = 2.现在,如果我通过导入此类(而不使用包名)尝试相同的操作:

returns x = 2 correctly. Now, if I try the same by importing this class (and not use the package name):

import myPack.myClass
y = myClass(2).prop

它给了我以下错误:

静态方法或构造函数调用无法编制索引. 不要使用以下方法调用静态方法或构造函数 任何其他索引或点引用.

Static method or constructor invocations cannot be indexed. Do not follow the call to the static method or constructor with any additional indexing or dot references.

为什么这在第一种情况下有效,而在第二种情况下无效?据我了解,import类的主要用途是允许人们使用类名而不使用长包名(除其他因素外).导致此错误的这两种区别是什么?我该如何解决?

Why does this work in the first case and not the second? As far as I understood, importing a class mainly allowed one to use the class name without the long package name (among other considerations). What is the difference in these two that causes this error and how can I work around it?

推荐答案

这对您来说更奇怪:如果您是在命令窗口,脚本或函数中运行,则行为会有所不同!

Here is some more weird for you: the behavior is different if you are running in the command window, from a script, or from a function!

这是您已经显示的内容

>> x = myPack.myClass(2).prop
x =
     2

>> import myPack.myClass; y = myClass(2).prop
Static method or constructor invocations cannot be indexed.
Do not follow the call to the static method or constructor with
any additional indexing or dot references. 

2)脚本(第一个:错误,第二个:错误)

testMyClassScript.m

x = myPack.myClass(2).prop
import myPack.myClass; y = myClass(2).prop

>> testMyClassScript
Static method or constructor invocations cannot be indexed.
Do not follow the call to the static method or constructor with
any additional indexing or dot references.
Error in testMyClassScript (line 1)
x = myPack.myClass(2).prop 

(第二行也会引发相同的错误)

(the second line would also throw the same error)

function testMyClassFunction()
    x = myPack.myClass(2).prop
    import myPack.myClass; y = myClass(2).prop
end

>> testMyClassFunction
x =
     2
y =
     2


我肯定会称其为错误:)预期的行为是在所有情况下都将出错.


I would definitely call that a bug :) The expected behavior is to give an error in all cases.

这篇关于导入类后,通过索引对静态方法进行调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆