'Importing Child Classes Dynamically in Python
I have an Employee abstract class that declares a getPhrase() method.
from abc import ABC, abstractmethod
class Employee(ABC):
def __init__(self, phrase):
self.phrase = phrase
return
@abstractmethod
def getPhrase(self):
pass
The implementations of this class are stored in separate files.
from Employee import Employee
class Doctor(Employee):
def __init__(self):
super().__init__("I love health!")
return
def getPhrase(self):
return self.phrase
The main application is an infinite loop that asks for the file paths to the Employee child class files. It should make an instance of the class and add it to an array of Employee's.
import importlib
import Employee
emp_list = []
while (True):
# to be replaced by a file picker
input_value = input("Enter file path or e to exit... ")
if (input_value == "e"):
break
module = importlib.import_module(input_value, ".")
# find Employee derived class inside the module
# make an instance of the class
emp = 0 # what do I put here?
# add the instance to an array
emp_list.append(emp)
# print all of the phrases
for e in emp_list:
print(e.getPhrase())
How do I use the import_module() method correctly? Heres the file structure:
project folder
|
+ - main.py
- Employee.py
- EmpFolder
|
+ - Doctor.py
- Teacher.py
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
