1

我有一个 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.pyuse2.py

有没有办法myprint()在不传递TAG参数的情况下在多个文件中使用该函数?

感谢您的回答!

4

2 回答 2

1

你应该检查一下functools.partial,这对这种事情非常有帮助。在定义 myprint 的文件中,定义一个通用函数:

def generic_myprint(tag, obj):
    print(f'{TAG} {obj}')

然后,在您要导入 myprint 的文件中,具有以下代码:

from functools import partial
from common import generic_myprint
myprint = partial(generic_myprint, tag='[USE1TAG]')

显然,tag为每个需要不同值的文件替换参数。

functools.partial接受一个具有许多参数的函数,并返回一个新partial对象,该对象的行为与原始函数完全相同,但具有一个或多个“预加载”参数作为默认值。在这种情况下,myprint现在只需要obj调用时的参数。generic_myprint接受 2 个参数,但myprint只接受 1 个。

在我看来,这比使用lambda函数更 Pythonic,但你的里程可能会有所不同!

https://docs.python.org/3/library/functools.html

于 2021-06-23T13:56:17.300 回答
0

实现这一点的一种方法是拥有一个返回正确配置的打印函数的函数,然后您可以使用该函数。为此,您可以使用 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
于 2021-06-23T12:48:21.480 回答