Backend Development
Python Tutorial
How to dynamically create an object through a string and call its methods in Python?
How to dynamically create an object through a string and call its methods in Python?

This article explains how to dynamically create objects through strings in Python and call their methods, which is very useful when you need to flexibly process objects based on configuration or runtime information. It is not possible to use strings directly, so it requires the help of Python's reflection mechanism.
The core lies in the getattr function, which receives object and attribute names (strings) as parameters. If the attribute exists, the attribute value is returned; otherwise, AttributeError exception is thrown. Combined with the importlib.import_module dynamic import module, we can implement dynamic creation and call.
Example:
Suppose we have two files: my_module.py defines classes and functions; main.py is responsible for dynamic calls.
my_module.py :
class MyClass:
def __init__(self, name):
self.name = name
def my_method(self):
print(f"Hello, {self.name}!")
def my_function():
print("This is a function.") main.py :
import importlib
module_name = "my_module"
class_name = "MyClass"
method_name = "my_method"
function_name = "my_function"
# Dynamic import module module = importlib.import_module(module_name)
# Dynamically create an object and call a method try:
my_class = getattr(module, class_name)("World")
getattr(my_class, method_name)() # Call method# Dynamically call the function getattr(module, function_name)()
except AttributeError as e:
print(f"Error: {e}") Running main.py will output:
<code>Hello, World! This is a function.</code>
This code demonstrates how to dynamically import modules through the strings module_name , class_name , method_name and function_name , create objects and call their methods and functions. try...except block handles possible AttributeError exceptions, improving code robustness. This provides an effective way to build flexible Python applications.
The above is the detailed content of How to dynamically create an object through a string and call its methods in Python?. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undresser.AI Undress
AI-powered app for creating realistic nude photos
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undress AI Tool
Undress images for free
Clothoff.io
AI clothes remover
AI Hentai Generator
Generate AI Hentai for free.
Hot Article
Hot Tools
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
1379
52
How to run programs in terminal vscode
Apr 15, 2025 pm 06:42 PM
In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.
What platform Docker uses to manage public images
Apr 15, 2025 am 07:06 AM
The Docker image hosting platform is used to manage and store Docker images, making it easy for developers and users to access and use prebuilt software environments. Common platforms include: Docker Hub: officially maintained by Docker and has a huge mirror library. GitHub Container Registry: Integrates the GitHub ecosystem. Google Container Registry: Hosted by Google Cloud Platform. Amazon Elastic Container Registry: Hosted by AWS. Quay.io: By Red Hat
What underlying technologies does Docker use?
Apr 15, 2025 am 07:09 AM
Docker uses container engines, mirror formats, storage drivers, network models, container orchestration tools, operating system virtualization, and container registry to support its containerization capabilities, providing lightweight, portable and automated application deployment and management.
What is vscode What is vscode for?
Apr 15, 2025 pm 06:45 PM
VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.
How to define header files for vscode
Apr 15, 2025 pm 09:09 PM
How to define header files using Visual Studio Code? Create a header file and declare symbols in the header file using the .h or .hpp suffix name (such as classes, functions, variables) Compile the program using the #include directive to include the header file in the source file. The header file will be included and the declared symbols are available.
Docker uses macvlan
Apr 15, 2025 am 06:57 AM
macvlan in Docker is a Linux kernel module that allows containers to have their own MAC address, enabling network isolation, performance improvement and direct interaction with the physical network. Using macvlan requires: 1. Install the kernel module; 2. Create a macvlan network; 3. Assign IP address segments; 4. Specify the macvlan network when container creation; 5. Verify the connection.
Can vscode be used on mac
Apr 15, 2025 pm 07:45 PM
VS Code performs well on macOS and can improve development efficiency. The installation and configuration steps include: installing VS Code and configuring. Install language-specific extensions (such as ESLint for JavaScript). Install the extensions carefully to avoid excessive startup slowing down. Learn basic features such as Git integration, terminal and debugger. Set the appropriate theme and code fonts. Note potential issues: extended compatibility, file permissions, etc.
Is the vscode extension malicious?
Apr 15, 2025 pm 07:57 PM
VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.


