📖 Python自習O_9o0 目次だぜ(^~^) - 目次
「 Python でクラスを動的に読み込むの、どうやるんだぜ?」
📖 How to Dynamically Load Modules or Classes in Python
📖 How to dynamically load a Python class
「 いろんな記事があって どれがベストプラクティスか分かんないのよね」
「 まず ふつうにクラスをロードしてみようぜ。
👇 以下のファイルを作成してくれだぜ」
└── 📂 src
└── 📂 hello
👉 └── 📄 __init__.py
class Hello:
def __init__():
pass
@classmethod
@property
def message(clazz):
return "Hello, world!!"
├── 📂 src
│ └── 📂 hello
│ └── 📄 __init__.py
└── 📂 tests
👉 └── 📄 hello_test.py
"""
python -m tests.hello_test
"""
from src.hello import Hello
print(Hello.message)
Input:
python -m tests.hello_test
Output:
Hello, world!!
「 これだと from src.hello import Hello
と、クラスの名前が埋め込んであるから、このクラスを読み込むな」
「 そのファイルか、クラスの名前を コマンドラインから指定したいのよ。
例えば」
python -m tests.hello_test src.welcome
「 from ~ import 文の名前ストラクチャーを教えてくれだぜ」
from src.hello import Hello
--------- -----
1 2
1. module name
2. class name
「 👆 これが代表的な例だぜ。こうじゃないケースもあるが今は省くぜ」
obj = load( module_name, class_name)
「 👆 こんな感じで クラスのインスタンスを取得できる関数が作れればいいわけかだぜ」
「 👇 サンプルコードを真似ようぜ。
以下のファイルを作成してくれだぜ」
├── 📂 src
│ ├── 📂 dimport
👉 │ │ └── 📄 __init__.py
│ └── 📂 hello
│ └── 📄 __init__.py
└── 📂 tests
└── 📄 hello_test.py
"""
📖 [How to Dynamically Load Modules or Classes in Python](https://www.geeksforgeeks.org/how-to-dynamically-load-modules-or-classes-in-python/)
📖 [How to dynamically load a Python class](https://stackoverflow.com/questions/547829/how-to-dynamically-load-a-python-class)
"""
class Dimport:
@staticmethod
def load(module_name, class_name):
# __import__ method used
# to fetch module
module = Dimport.load_module(module_name)
# getting attribute by
# getattr() method
return getattr(module, class_name)
@staticmethod
def load_module(name):
components = name.split('.')
mod = __import__(components[0])
for comp in components[1:]:
mod = getattr(mod, comp)
return mod
「 👇 サンプルコードを真似ようぜ。
以下のファイルを作成してくれだぜ」
├── 📂 src
│ ├── 📂 dimport
│ │ └── 📄 __init__.py
│ └── 📂 hello
│ └── 📄 __init__.py
└── 📂 tests
👉 ├── 📄 dimport_test.py
└── 📄 hello_test.py
"""
python -m tests.dimport_test
"""
from src.dimport import Dimport
print(Dimport.load("src.hello", "Hello").message)
Input:
python -m tests.dimport_test
Output:
AttributeError: module 'src' has no attribute 'hello'
「 👆 src
は hello
なんか持ってない、というエラーが出たぜ」
「 動的にインポートするときは ディレクトリーを自動で検索してくれないのか。じゃあ 手動で設定しようぜ」
├── 📂 src
│ ├── 📂 dimport
│ │ └── 📄 __init__.py
│ ├── 📂 hello
│ │ └── 📄 __init__.py
👉 │ └── 📄 __init__.py
└── 📂 tests
├── 📄 dimport_test.py
└── 📄 hello_test.py
from .hello import Hello
「 👆 src
が何を持ってるか 書いてやればいいわけだぜ」
Input:
python -m tests.dimport_test
Output:
Hello, world!!
├── 📂 src
│ ├── 📂 dimport
│ │ └── 📄 __init__.py
│ ├── 📂 hello
│ │ └── 📄 __init__.py
│ └── 📄 __init__.py
└── 📂 tests
├── 📄 dimport_test.py
👉 ├── 📄 dimport_test2.py
└── 📄 hello_test.py
"""
python -m tests.dimport_test2 -m src.hello -c Hello
"""
import argparse
from src.dimport import Dimport
# Command line arguments
ap = argparse.ArgumentParser()
ap.add_argument('-m', help='module')
ap.add_argument('-c', help='class')
args = ap.parse_args()
print(Dimport.load(args.m, args.c).message)
Input:
python -m tests.dimport_test2 -m src.hello -c Hello
Output:
Hello, world!!
📖 Python自習O1o0 Non-numeric Separated Value
おわり
Crieitは誰でも投稿できるサービスです。 是非記事の投稿をお願いします。どんな軽い内容でも投稿できます。
また、「こんな記事が読みたいけど見つからない!」という方は是非記事投稿リクエストボードへ!
こじんまりと作業ログやメモ、進捗を書き残しておきたい方はボード機能をご利用ください。
ボードとは?
コメント