1 回答
TA贡献1806条经验 获得超8个赞
我编写了一个小解决方案,将自定义 matlab 类与 oct2py 一起使用。目前,这种方法仅支持访问 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)
注意:您可能需要在 Octave 代码中使用 init 函数来运行设置 Value 变量。
添加回答
举报