python将位置参数传递给另一个函数调用
有人能给我解释一下下面的工作原理吗python将位置参数传递给另一个函数调用,python,function-calls,Python,Function Calls,有人能给我解释一下下面的工作原理吗 class Memoize: def __init__(self, f): self.f = f self.memo = {} def __call__(self, *args): if not args in self.memo: self.memo[args] = self.f(*args) return self.memo[args] 然后: 我发现
class Memoize:
def __init__(self, f):
self.f = f
self.memo = {}
def __call__(self, *args):
if not args in self.memo:
self.memo[args] = self.f(*args)
return self.memo[args]
然后:
我发现语法错误。我以为是开包操作员之类的。带元组的星号是独立的还是只存在于函数调用的上下文中?谢谢您的解释。它/是/是一名拆包操作员。然而,当直接在解释器中调用时,它并不总是这样工作。看看这个:
In [90]: def addThese(a,b,c):
....: print 'a', a
....: print 'b', b
....: print 'c', c
....: print 'a+b+c', a+b+c
....: return a+b+c
....:
In [91]: args = (1,3,5)
In [92]: addThese(1,3,5)
a 1
b 3
c 5
a+b+c 9
Out[92]: 9
In [93]: addThese(args)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-93-cc47562f352a> in <module>()
----> 1 addThese(args)
TypeError: addThese() takes exactly 3 arguments (1 given)
In [94]: addThese(*args)
a 1
b 3
c 5
a+b+c 9
Out[94]: 9
[90]中的:定义添加这些(a、b、c):
..:打印“a”,a
..:打印“b”,b
..:打印“c”,c
..:打印“a+b+c”,a+b+c
..:返回a+b+c
....:
在[91]中:args=(1,3,5)
在[92]中:添加这些(1,3,5)
a 1
b 3
C5
a+b+c 9
Out[92]:9
在[93]中:添加这些(args)
---------------------------------------------------------------------------
TypeError回溯(最近一次调用上次)
在()
---->1添加这些(args)
TypeError:AddThises()只接受3个参数(给定1个)
在[94]中:添加这些(*args)
a 1
b 3
C5
a+b+c 9
Out[94]:9
没错,它只存在于函数调用的上下文中。谢谢@BrenBarn的回答。
*(1,2,3)
In [90]: def addThese(a,b,c):
....: print 'a', a
....: print 'b', b
....: print 'c', c
....: print 'a+b+c', a+b+c
....: return a+b+c
....:
In [91]: args = (1,3,5)
In [92]: addThese(1,3,5)
a 1
b 3
c 5
a+b+c 9
Out[92]: 9
In [93]: addThese(args)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-93-cc47562f352a> in <module>()
----> 1 addThese(args)
TypeError: addThese() takes exactly 3 arguments (1 given)
In [94]: addThese(*args)
a 1
b 3
c 5
a+b+c 9
Out[94]: 9