从Oct2Py返回类对象



我正在尝试运行一个定义类的基本MATLAB脚本,并将该类对象返回到python。我不太了解MATLAB,而且对Oct2Py很陌生,所以我可能完全误解了如何做到这一点。如有任何帮助,我们将不胜感激。

这是Matlab文件(取自此处(

classdef BasicClass
properties
Value {mustBeNumeric}
end
methods
function r = roundOff(obj)
r = round([obj.Value],2);
end
function r = multiplyBy(obj,n)
r = [obj.Value] * n;
end
end
end

我用下面的在python脚本中调用它

from oct2py import octave
octave.addpath(r'C:Usersi13500020.spyder-py3IST')
oclass = octave.class_example(nout=1)

当我运行这个程序时,我会收到一个打印四次的警告,然后是一条错误消息

第一:

warning: struct: converting a classdef object into a struct overrides the access restrictions defined for properties. All properties are returned, including private and protected ones.

然后:

TypeError: 'NoneType' object is not iterable

我从Oct2Py页面运行往返示例没有任何问题,所以我知道我的安装很好

我写了一个小的变通方法,用oct2py使用自定义的matlab类。目前,这种方法只支持访问Matlab类的成员函数(而不是属性(,因为这正是我所需要的:

from oct2py import octave
class MatlabClass():
_counter = 0
def __init__(self, objdef) -> None:
"""Use matlab object as python class.
Args:
objdef (str): Class initialization as string.
"""
MatlabClass._counter += 1
self.name = f"object_for_python{MatlabClass._counter}"
octave.eval(f"{self.name} = {objdef};")

def __getattr__(self, item):
"""Maps values to attributes.
Only called if there *isn't* an attribute with this name
"""
def f(*args):
call = f"{self.name}.{item}({','.join([str(arg) for arg in args])});"
return octave.eval(call)
return f

按如下方式使用此类:

param = 0.24 # random value you might need for class initialization
oclass = MatlabClass(f"BasicClass({param})")
x = oclass.roundOff()
y = oclass.multiplyBy(2)

注意:您可能需要在倍频程代码中使用init函数来运行设置Value变量。

相关内容

  • 没有找到相关文章

最新更新