実現したいこと
Pythonのexecメソッドで文字列からクラスを生成したいです。
クラスを生成するところまでは成功しましたが、
同じ処理をメソッド内に移行して動かしたところで、エラーが発生して困っています。
以下コードで文字列から、testクラスを生成できました。
python
1txt = ''' 2class test: 3 x = 1 4 y = "a" 5''' 6exec(txt) 7print(test.x)
output
11
発生している問題・エラーメッセージ
次に、メソッド内で上と同じ処理を実行したところ、
以下のようにtestクラスが定義されていないとのエラーが発生しました。
python
1def sample(): 2 txt = ''' 3class test: 4 x = 1 5 y = "a" 6''' 7 exec(txt) 8 print(test.x) 9 10print(sample())
output
1Traceback (most recent call last): 2 File "~", line 10, in <module> 3 print(sample()) 4 File "~", line 8, in sample 5 print(test.x) 6NameError: name 'test' is not defined
ご教授いただけると幸いです。
回答1件
あなたの回答
tips
プレビュー