开发者

Programatically importing a file and creating an instance of a class in Python

开发者 https://www.devze.com 2022-12-28 17:08 出处:网络
I have a (python) list of strings which refer to python source files and subsequently classes within those files which I want to import and then create an instance of the classes within the files (eve

I have a (python) list of strings which refer to python source files and subsequently classes within those files which I want to import and then create an instance of the classes within the files (everything follows a strict naming convention, making this theoretically possible), in Ruby I would do something like:

require "lib/sources/#{source}.rb"
开发者_JAVA技巧s = source.constantize.new

How would I do something similar in Python?

Thanks, Ben


Please see Dynamic Module Loading in Python:

If you have a need to import a module in python and, for whatever reason, you will not know the name of the module until run-time, python provides the built-in __import__ function.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号