简体   繁体   English

为什么这不可能在Python中?

[英]Why isn't this possible in Python?

def myfunc(a,b=2):
    print("Called with", a, b)
    return
p1 = functools.partial(myfunc, b=4)
p1("foobar", 4)

Why do I get a syntax error when I run that last line? 为什么运行最后一行时会出现语法错误? It works if i do: myfunc("foobar", 4) myfunc("foobar", 4)如果我这样做: myfunc("foobar", 4)

'partial' already sets 'b' to 4; 'partial'已将'b'设为4; if you want another value you should explicitely set parameter 'b': 如果你想要另一个值,你应该明确地设置参数'b':

>>> p1("foobar")
('Called with', 'foobar', 4)

>>> p1("foobar", b=5)
('Called with', 'foobar', 5)

Because you are supplying it with a b in functools.partial call. 因为你在functools.partial调用中提供了b Your call should look like: 你的电话应该是这样的:

p1("foobar")

or you could just get rid of b=4 in p1 = functools.partial(myfunc, b=4) and make it something like: 或者你可以在p1 = functools.partial(myfunc, b=4)摆脱b=4 ,并使它像:

p1 = functools.partial(myfunc)

I think this is because python allows you to use optional parameters in any order. 我认为这是因为python允许您以任何顺序使用可选参数。 When you work with more statically typed languages, there is usually a constraint on using optional parameters in the order defined in the function/method. 使用更多静态类型语言时,通常会在函数/方法中定义的顺序中使用可选参数。 So for instance, in python this is legal: 所以,例如,在python中这是合法的:

def myfunc(a=1,b=2,c=3):
    print a,b,c

myfunc(c=99, b=13, a=12)

Because you can specify optional parameters in any order, I think python explicitly needs to know which parameters are assigned to which local function variables. 因为您可以按任何顺序指定可选参数,我认为python显然需要知道哪些参数分配给哪些本地函数变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM