我有一个 python 文件,假设它是common.py
在此,我有一些函数,以及函数所需的变量:
TAG = '[TESTTAG]'
def myprint(obj):
print(f'{TAG} {obj}')
def set_tag(out_tag):
global TAG
TAG = out_tag
我希望能够使用该myprint()
函数而不必TAG
每次都传递参数。为了设置这个TAG
,我编写了set_tag()
函数
我还有 2 个其他文件,我想在其中使用该myprint()
功能,但标签不同:use1.py
from common import *
set_tag('[USE1TAG]')
def testusage():
myprint('First sentence')
myprint('Second sentence')
if __name__ == '__main__':
testusage()
使用2.py
from common import *
set_tag('[USE2TAG]')
def testusage2():
myprint('Third sentence')
myprint('Fourth sentence')
if __name__ == '__main__':
testusage2()
当我单独运行它们时,它们会产生预期的结果。
但问题是我想将这两个文件都导入到最终文件中,并多次使用它们的功能,每次都使用TAG
我之前在其源文件中设置的 。这样,最新导入的文件将更TAG
改为[USE2TAG]
,并且将继续使用。
结合.py
from use1 import testusage
from use2 import testusage2
if __name__ == '__main__':
testusage()
testusage2()
testusage()
testusage2()
输出:
[USE2TAG] First sentence
[USE2TAG] Second sentence
[USE2TAG] Third sentence
[USE2TAG] Fourth sentence
[USE2TAG] First sentence
[USE2TAG] Second sentence
[USE2TAG] Third sentence
[USE2TAG] Fourth sentence
预期结果:
[USE1TAG] First sentence
[USE1TAG] Second sentence
[USE2TAG] Third sentence
[USE2TAG] Fourth sentence
[USE1TAG] First sentence
[USE1TAG] Second sentence
[USE2TAG] Third sentence
[USE2TAG] Fourth sentence
问题是它们对同一个TAG
变量进行操作。我知道,我每次都可以将 传递TAG
给函数,但我认为必须有一种方法可以不使用它。myprint()
我知道我可以为 the和定义myprint()
函数,但我宁愿将它作为“服务”导入,所以我不必每次都附加它。use1.py
use2.py
有没有办法myprint()
在不传递TAG
参数的情况下在多个文件中使用该函数?
感谢您的回答!