When creating a script that makes a judgment according to the rules
I wanted to be able to add rules, so I created it
Made it possible to execute by creating a class that inherits Person in classes
.
├── Main.py
└── classes
├── Person.py
├── Taro.py
└── Tom.py
Main.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# from os.path import join, relpath, splitext
from os import path
from glob import glob
import re
import sys
def main():
""" Run from Here. """
dir = "classes"
exception_file = ["__pycache__", "Person.py"]
extention = ".py"
reg = re.compile('.+\\' +extention)
sys.path.append(dir) #Add path
files = [path.relpath(x, dir) for x in glob(path.join(dir, '*'))]
files = list(set(files) - set(exception_file))
objs = []
for x in files:
if reg.match(x):
name = x.replace(".py", "")
#Load class here
m = __import__(name, globals(), locals(), [name], 0 )
o = eval("m."+name+"()")
objs.append(o)
for obj in objs:
obj.say()
if __name__=="__main__":
main()
Person.py
from abc import ABCMeta
from abc import abstractmethod
class Person(metaclass=ABCMeta):
@abstractmethod
def say(self):
raise NotImplementedError
Taro.py
from Person import Person
class Taro(Person):
def say(self):
print("Hello, this is Taro.")
Tom.py
from Person import Person
class Tom(Person):
def say(self):
print("Hello, this is Tom.")
out
$ python Main.py
Hello, this is Taro.
Hello, this is Tom.
Is it dangerous to implement a script that can be added without rewriting the program?
Is there a smarter way to call?
Please tell me
Recommended Posts