Why do I encounter the error "AttributeError: 'matlab.object' object has no attribute 'getBalance'" when using a MATLAB class compiled as a Python package?

Is it possible to compile a MATLAB class into a Python package, create an instance of that class in Python, and use its methods?
I have successfully compiled a class into a Python package, installed the package in Python, initialized the package, and created an object of the class by calling the constructor. 
However, I am unable to use any of the methods of the created class object. I receive the error
"AttributeError: 'matlab.object' object has no attribute 'getBalance',"
where "getBalance" is one of the class methods.
Is there a way to use the methods of the class, or is this not possible?

 採用された回答

MathWorks Support Team
MathWorks Support Team 2025 年 1 月 27 日
編集済み: MathWorks Support Team 2025 年 1 月 27 日
As of R2023b, Compiler SDK for Python does not support calling MATLAB class member functions directly. For every member function that you want to call in Python, you will need to add a standalone function and package them together with the MATLAB class files.
In order to call the "deposit" member function in Account class, you can create an M file with a function that calls this member function. As an example, you can create a file named "Account_deposit.m" and place this file in the same location as "Account.m":
function new_balance = Account_deposit(account, deposit)
    account.deposit(deposit);
    new_balance = account.Balance;
end  
When compiling the Python package, you need to include "Account_deposit.m". To do this, execute the following command in the MATLAB Command Window:
>> buildResults = compiler.build.pythonPackage(["Account.m", "Account_deposit.m"], 'PackageName', 'AccountPkg', 'Verbose', 'on');
After creating the package, navigate to the package folder. The package name should be "AccountPkgpythonPackage". You should see a "setup.py" file along with other files. Install the created Python package from the MATLAB Command Window using the following instruction:
!python setup.py install
Then you can call the "Account_deposit" function in Python as follows: 
>>> import AccountPkg
>>> my_AccountPkg = AccountPkg.initialize()
>>> account_obj = my_AccountPkg.Account()
>>> deposit_amount = 100.0
>>> balance = my_AccountPkg.Account_deposit(account_obj, deposit_amount)
>>> balance
If there are other methods or properties you want to access from Python, you can add standalone MATLAB functions in a similar fashion.

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File Exchange で Python Package Integration についてさらに検索

製品

リリース

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by