フィルターのクリア

Call Python class from MATLAB

44 ビュー (過去 30 日間)
Mathieu
Mathieu 2018 年 3 月 1 日
コメント済み: nanren888 2022 年 4 月 18 日
Hello,
Is it possible to call a Python class from MATLAB ? I found how to call Python functions in a .py file but not really how to deal with class.
For example, how to get/set the attribute of the following class and use its method from MATLAB:
class MyClass:
"""A simple example class"""
i = 12345
def f(self):
return 'hello world'
Thank you in advance for any advice/help.
  1 件のコメント
Hisham Assi
Hisham Assi 2021 年 3 月 12 日
Hi Mathieu,
I have the same questiion; did you figure it out?
Thanks,
Hisham.

サインインしてコメントする。

回答 (1 件)

Hans-Joachim Steinort
Hans-Joachim Steinort 2021 年 8 月 30 日
編集済み: Hans-Joachim Steinort 2021 年 8 月 30 日
This answer might be plentifully late, but I currently stumble across the same topic, so for anybody who needs this in the future:
I copied your example class to a python-file named Test_Py.py in my current folder.
Then you first create a matlab object like so:
pyClass = py.Test_Py.MyClass
Th function call then is pretty straight forward:
s = pyClass.f;
S is now an object Python str with no properties as displayed if you simply use the disp(s) command
>> disp(s)
Python str with no properties.
hello world
Matlab provides an internal conversion between python data types and Matlab datatypes (see Documentation). This creates the desired output:
>> disp(string(s))
hello world
  2 件のコメント
nanren888
nanren888 2022 年 4 月 18 日
編集済み: nanren888 2022 年 4 月 18 日
Unable to resolve the name py.Test_Py.MyClass.
The function examples from the "Call User-Defined Python Module" work fine.
As soon as there's a class in the file, I get nothing but "Unable to resolve".
Has there been a change?
There's something really obvious missing?
nanren888
nanren888 2022 年 4 月 18 日
Resolved, probably.
Found
py.importlib.import_module('Test_Py') - to actually produce a useful error.
And seems caught by the old copy-paste from website example produces inconsistent indentation problem.
I so like languages with syntax relying on invisibles. :)

サインインしてコメントする。

カテゴリ

Help Center および File ExchangePython Package Integration についてさらに検索

製品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by