How can I instantiate a class from a python module that I imported with py.importlib.import_module?
19 views (last 30 days)
Show older comments
MathWorks Support Team
on 7 Apr 2021
Answered: MathWorks Support Team
on 23 Apr 2021
I have the following python class saved in a module named vehicleClass.py:
class Vehicle:
@staticmethod
def myMethod():
return 3
def __init__(self, brand, model, type):
self.brand = brand
self.model = model
self.type = type
self.gas_tank_size = 14
self.fuel_level = 0
def fuel_up(self):
self.fuel_level = self.gas_tank_size
print('Gas tank is now full.')
In MATLAB, I then import the module using:
>> vMod = py.importlib.import_module('vehicleClass')
I have tried using tab-complete to figure out how to instantiate my class in MATLAB but I can't find the constructor. How can I do this?
Accepted Answer
MathWorks Support Team
on 7 Apr 2021
If you decide to import your module this way, you can use the feval method to instantiate your class. In this case, you can instantiate your class using:
>> myVehicle = vMod.Vehicle.feval("a","b","c")
myVehicle =
Python Vehicle with properties:
model: [1×1 py.str]
fuel_level: [1×1 py.int]
gas_tank_size: [1×1 py.int]
type: [1×1 py.str]
brand: [1×1 py.str]
<vehicleClass.Vehicle object at 0x000001CB2EFC61F0>
Alternatively, you can instantiate your class using:
>> myVehicle = py.vehicleClass.Vehicle("a","b","c")
myVehicle =
Python Vehicle with properties:
model: [1×1 py.str]
fuel_level: [1×1 py.int]
gas_tank_size: [1×1 py.int]
type: [1×1 py.str]
brand: [1×1 py.str]
<vehicleClass.Vehicle object at 0x000002AB6FF3BF10>
With this method, you do not have to import your module using py.importlib.import_module(...).
0 Comments
More Answers (0)
See Also
Categories
Find more on Call Python from MATLAB in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!