How can I instantiate a class from a python module that I imported with py.importl​ib.import_​module?

조회 수: 17 (최근 30일)
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
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개)

카테고리

Help CenterFile Exchange에서 Call Python from MATLAB에 대해 자세히 알아보기

태그

아직 태그를 입력하지 않았습니다.

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by