-1

For example, my package path is component.sub_fold.package.class_name. The component.sub_fold is the path of my package. The package is a file name. The class_name is a class name which I want to initialize it. I can initialize an object through

from component.sub_fold.package import class_name

obj = class_name()

How can I initialize an object through the string "component.sub_fold.package.class_name"?

0

1 Answer 1

0

If you want to programmatically import a module by specifying its name, you could use the importlib module.

import importlib

name = 'component.sub_fold.package.class_name'
pkg, symbol = name.rsplit('.', maxsplit=1)

pkg = importlib.import_module(pkg)
obj = getattr(pkg, symbol)()
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your reply. I finally found my question was associated with another similar questions.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.