Câu hỏi phỏng vấn Python
Câu hỏi

How can you share global variables across modules?

Câu trả lời

To share global variables across modules in Python, you can use several approaches, each with its own advantages and considerations. Here are the primary methods:

1. Using a Config Module

One common and effective way to share global variables across different modules is to create a dedicated configuration module, often named config.py or cfg.py. This module contains the global variables you want to share.

  • Create a config module: Define all your global variables in this module.
  • Import the config module: In every other module where you need access to these global variables, import the config module. This approach ensures that there is only one instance of each variable, and any changes made to these variables are reflected across all modules that import this config module.

For example:

python Copy
# config.py
x = 0

# mod.py
import config
config.x = 1

# main.py
import config
import mod
print(config.x)  # Output will be 1

This method is straightforward and maintains consistency across modules by ensuring that all modules refer to the same instance of each variable[1][4].

2. Using a Global Variables Module

Similar to the config module approach, you can create a module specifically for global variables. This method centralizes all global variables in one location, making management and updates easier.

  • Create a global variables module: This module will store all the global variables.
  • Import this module wherever needed: Just like with the config module, you import this global variables module in any other module where you need access to the globals.

Example:

python Copy
# globals.py
variable1 = 0

# usage in another module
import globals
globals.variable1 = 100

This method is also reflected in various sources as a practical approach to managing global variables ac...

middle

middle

Gợi ý câu hỏi phỏng vấn

middle

What is the function of self ?

senior

What is Cython?

middle

What are Decorators in Python?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào