How can I instantiate a class from a python module that I imported with py.importlib.import_module?
17 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
MathWorks Support Team
el 7 de Abr. de 2021
Respondida: MathWorks Support Team
el 23 de Abr. de 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?
Respuesta aceptada
MathWorks Support Team
el 7 de Abr. de 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 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Call Python from MATLAB en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!