LoginSignup
8
6

More than 5 years have passed since last update.

プラグインできるタイプの実装が作りたい

Posted at

ルールに従い判定を行うスクリプトを作成時

ルールは追加できるようにしたかったので作成

Personを継承したクラスを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) # 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", "")
            # ここでクラスの読み込み
            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.

分からない点

プログラムを書き換えること無くスクリプトを追加できる実装は危険なのか

もっとスマートにかける方法ないのか

教えて下さい

8
6
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
6