亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從 Oct2Py 返回類對象

從 Oct2Py 返回類對象

慕無忌1623718 2023-09-19 14:12:01
我正在嘗試運行一個定義類的基本 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   endend我在 python 腳本中使用以下命令調用它from oct2py import octaveoctave.addpath(r'C:\Users\i13500020\.spyder-py3\IST')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 頁面運行往返示例沒有任何問題,所以我知道我的安裝沒問題
查看完整描述

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 變量。


查看完整回答
反對 回復 2023-09-19
  • 1 回答
  • 0 關注
  • 124 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號