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

7 Ansichten (letzte 30 Tage)
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?

Akzeptierte Antwort

MathWorks Support Team
MathWorks Support Team am 27 Jan. 2025
Bearbeitet: MathWorks Support Team am 27 Jan. 2025
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.

Weitere Antworten (0)

Kategorien

Mehr zu Python Package Integration finden Sie in Help Center und File Exchange

Produkte


Version

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by