我注意到 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.
关于Python kwarg 共享实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42000125/