gpt4 book ai didi

python - 作为默认函数参数的函数调用

转载 作者:太空狗 更新时间:2023-10-30 00:42:54 24 4
gpt4 key购买 nike

拥有

# example.py

def foo(arg=bar()):
pass

即使使用 from example import foo 也会执行 bar

我记得很久以前我看到过这样的东西:

# example.py

def foo(arg=lambda: bar()):
pass

但我不确定这是否是最好的方法,而现在,当我遇到这种情况时,我找不到任何关于如何处理这种行为的信息。

在 python 中将函数调用作为默认函数参数的正确方法是什么?

最佳答案

这是最Python化的方式:

def foo(arg=None):
if arg is None:
arg = bar()
...

如果您希望函数 bar 只被调用一次,并且不希望它在导入时被调用,那么您将不得不在某处维护该状态em>。也许在可调用类中:

class Foo:

def __init__(self):
self.default_arg = None

def __call__(self, arg=None):
if arg is None:
if self.default_arg is None:
self.default_arg = bar()
arg = self.default_arg
...

foo = Foo()

关于python - 作为默认函数参数的函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45718318/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com