英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论