初始化整个Python包的变量

问题描述 投票:0回答:1

我构建了一个包含不同模块的包。 一切正常,但我在初始化变量时遇到问题。 在包中,我需要一个 init() 函数来初始化变量。 我怎样才能使这个变量在我的所有模块/函数中可用?

我尝试了不同的方法,但只能部分起作用。

my_package
  init.py
    init()
  my_module
    my_function.py   <---- How to use x?


**init.py**
  global x
  def init():
   global x
   x=1

我希望能够做到:

import my_package
my_package.init(1234)

my_package.my_module.my_function() <---- Should be able to use x with its 1234 value
python module package namespaces python-import
1个回答
0
投票

我想你想要这样的东西:

init.py

x = 1 # or whatever value
def init(y):
    global x
    x=y
© www.soinside.com 2019 - 2024. All rights reserved.