Question
How can I dynamically instantiate a class in Python using its name as a string, similar to Java's Class.forName()?
class MyClass:
def __init__(self):
print('MyClass instance created!')
# Dynamic instantiation example
your_class_name = 'MyClass'
instance = globals()[your_class_name]()
Answer
In Python, you can achieve functionality similar to Java's Class.forName() method by utilizing built-in functions like `globals()`, `locals()`, or `getattr()`. These allow you to dynamically access and instantiate classes using their names as strings.
import mymodule
class MyClass:
def __init__(self):
print('MyClass instance created!')
# Using `getattr` to dynamically create an instance
your_class_name = 'MyClass'
instance = getattr(mymodule, your_class_name)()
Causes
- The need to instantiate a class based on its name provided as a string.
- The requirement to use command-line arguments for dynamic class instantiation.
Solutions
- Use the `globals()` function to access a class if it's defined in the global scope.
- Utilize `getattr()` if the class is a member of a module or a specific namespace.
- Leverage `locals()` to access classes defined in the local context.
Common Mistakes
Mistake: Not importing the module where the class is defined.
Solution: Ensure the module that contains the class is imported before attempting to access the class.
Mistake: Using the wrong scope to access the class (global vs local).
Solution: Verify the scope where the class is defined and use `globals()` or `locals()` appropriately.
Helpers
- Python equivalent of Class.forName
- dynamically instantiate class in Python
- getattr() in Python
- Python class from string
- Java Class.forName equivalent Python