我只想为第一个变量设置一个默认值,但我不能。

huangapple go评论62阅读模式
英文:

I Just Want to Set a Default Value to the First Variable but I can't

问题

I want to arrange my function's variables. When i try to add to the first one default value i am getting a SyntaxError.

class a():
    def __init__(self,b = "hey",c,d):
        self.b = b
        self.c = c
        self d = d
    def __init__(self,b = "hey",c,d):
                                ^
SyntaxError: non-default argument follows default argument

But when I try to add to the last one I don't get any error.

class a():
    def __init__(self,b,c,d = "hey"):
        self.b = b
        self.c = c
        self.d = d

I just want to edit the default value of a middle or first variable. How can i do it?

英文:

I want to arrange my function's variables. When i try to add to the first one default value i am getting a SyntaxError.

class a():
    def __init__(self,b = "hey",c,d):
        self.b = b
        self.c = c
        self.d = d
    def __init__(self,b = "hey",c,d):
                                ^
SyntaxError: non-default argument follows default argument

But when I try to add to the last one I don't get any error.

class a():
    def __init__(self,b,c,d = "hey"):
        self.b = b
        self.c = c
        self.d = d

I just want to edit the default value of a middle or first variable. How can i do it?

答案1

得分: 2

你可以通过使用仅限关键字参数来实现这一点,可以通过在参数列表中添加*来指定:

class a():
    def __init__(self, *, b="hey", c, d):
        self.b = b
        self.c = c
        self.d = d

如果参数是按位置指定的,并且其中一些具有默认值,那么哪个参数是哪个参数可能会不明确,这就是为什么不允许这样做的原因(除非所有默认值都位于末尾,在这种情况下,通过在需要的参数后按顺序重新绑定所有默认值来解决歧义)。

如果参数总是作为关键字参数指定,那么就没有歧义,因为您始终指示哪个参数是哪个参数。

英文:

You can do this if you use keyword-only arguments, which you can specify by adding a * to the arg list:

class a():
    def __init__(self, *, b = "hey", c, d):
        self.b = b
        self.c = c
        self.d = d

If the arguments are specified positionally and some of them have defaults, it can be ambiguous which argument is which, which is why this is disallowed (unless all the defaults are at the end, in which case the ambiguity is resolved by rebinding all the defaults in order after the required arguments).

If the arguments are always specified as keyword arguments, there is no ambiguity because you always indicate which argument is which.

huangapple
  • 本文由 发表于 2023年3月7日 01:48:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/75654153.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定