我在路径myClass.m
中的包文件夹+myPack
中有一个类文件.类文件的一个简单示例是:
classdef myClass
properties
prop
end
methods
function obj = myClass(x)
obj.prop = x;
end
end
end
Run Code Online (Sandbox Code Playgroud)
现在,如果我直接调用该方法并使用完整包名访问该属性,即:
x = myPack.myClass(2).prop;
Run Code Online (Sandbox Code Playgroud)
x = 2
正确返回.现在,如果我通过导入此类(而不是使用包名称)尝试相同的操作:
import myPack.myClass
y = myClass(2).prop
Run Code Online (Sandbox Code Playgroud)
它给了我以下错误:
无法索引静态方法或构造函数调用.不要使用任何其他索引或点引用来跟随对静态方法或构造函数的调用.
为什么这在第一种情况下工作而不是第二种情况?据我所知,import
一个类主要允许一个人使用没有长包名的类名(以及其他考虑因素).这两个导致此错误的区别是什么,我该如何解决?
这里有一些更奇怪的东西:如果你在命令窗口,脚本或函数中运行,行为就会有所不同!
这就是你已经展示过的
>> 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.
Run Code Online (Sandbox Code Playgroud)
x = myPack.myClass(2).prop
import myPack.myClass; y = myClass(2).prop
Run Code Online (Sandbox Code Playgroud)
和
>> 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
Run Code Online (Sandbox Code Playgroud)
(第二行也会抛出相同的错误)
function testMyClassFunction()
x = myPack.myClass(2).prop
import myPack.myClass; y = myClass(2).prop
end
Run Code Online (Sandbox Code Playgroud)
和
>> testMyClassFunction
x =
2
y =
2
Run Code Online (Sandbox Code Playgroud)
我肯定会称这是一个错误:)预期的行为是在所有情况下都给出错误.