How can I instantiate a class from a python module that I imported with py.importlib.import_module?
17 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
MathWorks Support Team
le 7 Avr 2021
Réponse apportée : MathWorks Support Team
le 23 Avr 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?
Réponse acceptée
MathWorks Support Team
le 7 Avr 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 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Call Python from MATLAB dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!