我有一个 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()
函数,但我认为必须有一种方法可以不使用它。
我知道我可以myprint()
为 theuse1.py
和 the定义函数use2.py
,但我宁愿将它作为“服务”导入,所以我不必每次都附加它。
有没有办法myprint()
在不传递TAG
参数的情况下在多个文件中使用该函数?
感谢您的回答!
实现此目的的一种方法是使用一个函数返回正确配置的打印函数,然后您可以使用该函数。为此,您可以使用 lambda。例如:
def _myprint(tag, obj):
print(f'[{tag}] {obj}')
def get_myprint(tag):
return lambda obj, tag=tag: _myprint(tag, obj)
然后在使用它的地方,您可以执行以下操作:
print_a = get_myprint('a')
print_b = get_myprint('b')
print_a('test a')
print_b('test b')
这使
[a] test a
[b] test b
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句