teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

3

修正

2020/08/26 11:27

投稿

tiitoi
tiitoi

スコア21960

answer CHANGED
@@ -49,4 +49,12 @@
49
49
  func = getattr(inst, func_name)
50
50
 
51
51
  func() # func called
52
+ ```
53
+
54
+ /data/notebook/test/a.py
55
+
56
+ ```python
57
+ class MyClass:
58
+ def func(self):
59
+ print("func called")
52
60
  ```

2

修正

2020/08/26 11:27

投稿

tiitoi
tiitoi

スコア21960

answer CHANGED
@@ -32,17 +32,21 @@
32
32
 
33
33
  ```python
34
34
  import importlib.util
35
+ from pathlib import Path
35
36
 
37
+ module_path = "/data/notebook/test/a.py"
38
+ class_name = "MyClass"
36
- import importlib
39
+ func_name = "func"
37
40
 
38
- module_path = "/data/notebook/test/a.py" # ファイルのある場所
39
- module_name = "a"
41
+ module_path = Path(module_path)
40
- func_name = "func_a"
41
-
42
- spec = importlib.util.spec_from_file_location(module_name, module_path)
42
+ spec = importlib.util.spec_from_file_location(module_path.stem, module_path)
43
43
  module = importlib.util.module_from_spec(spec)
44
44
  spec.loader.exec_module(module)
45
45
 
46
+ MyClass = getattr(module, class_name)
47
+
48
+ inst = MyClass()
46
- func = getattr(module, func_name)
49
+ func = getattr(inst, func_name)
50
+
47
- func()
51
+ func() # func called
48
52
  ```

1

修正

2020/08/26 11:27

投稿

tiitoi
tiitoi

スコア21960

answer CHANGED
@@ -26,4 +26,23 @@
26
26
  ```python
27
27
  def func_b():
28
28
  print("b.func_b")
29
+ ```
30
+
31
+ ## 追記
32
+
33
+ ```python
34
+ import importlib.util
35
+
36
+ import importlib
37
+
38
+ module_path = "/data/notebook/test/a.py" # ファイルのある場所
39
+ module_name = "a"
40
+ func_name = "func_a"
41
+
42
+ spec = importlib.util.spec_from_file_location(module_name, module_path)
43
+ module = importlib.util.module_from_spec(spec)
44
+ spec.loader.exec_module(module)
45
+
46
+ func = getattr(module, func_name)
47
+ func()
29
48
  ```