How can I instantiate a class from a python module that I imported with py.importlib.import_module?
조회 수: 17 (최근 30일)
이전 댓글 표시
MathWorks Support Team
2021년 4월 7일
답변: MathWorks Support Team
2021년 4월 23일
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?
채택된 답변
MathWorks Support Team
2021년 4월 7일
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
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Call Python from MATLAB에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!