Python kwarg 共享实例

标签 python keyword-argument

我注意到 python 中的 kwargs 出现了我没有预料到的效果,我想确认我已经完全理解它/获得更好的理解。

我的示例代码

class Obj(object):
    pass

def Foo(kwarg=Obj()):
     return kwarg

def Bar(kwarg=None):
     if not kwarg:
         kwarg = Obj()
     return kwarg

现在我直到最近才明白这些函数做了一些不同的事情。

除非调用时传递kwarg,否则Foo每次都会返回相同的Obj实例,而Bar每次都会返回不同的Obj实例。

发生这种情况是因为关键字参数在编译时被分配给其 RHS 的解析值,导致每次都在同一实例中返回相同的值。

最佳答案

你明白了,但是在 vanilla python 中没有编译。 :) 这里引用了《Python 漫游指南》:

Python’s default arguments are evaluated once when the function is defined, not each time the function is called (like it is in say, Ruby). This means that if you use a mutable default argument and mutate it, you will and have mutated that object for all future calls to the function as well.

http://docs.python-guide.org/en/latest/writing/gotchas/

关于Python kwarg 共享实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42000125/

相关文章:

python - 如何修改 .bash_profile 文件,以便无需输入文件路径即可运行 python 脚本?

python - SQLAlchemy 连接如何与基于 session 的事务相关?

python - 如何在 Python 的包装函数中使用任意函数

Ruby 在关键字参数与位置混合中的奇怪行为

function - 使用相同变量定义函数的最优雅/有效的方法

Python headless MatplotLib/Pyplot

python - 如何在 Django 模板中对齐文本或 url? - Python 速成类(class),元素 "Learning Log"

python - 使用Python读取文件夹中的wav文件

Python:发现可接受的关键字参数

python - 如何打印 args 和 kwargs 列表