【发布时间】:2014-06-06 05:41:57
【问题描述】:
在我正在查看的代码中,我看到了一些这样的类方法:
class A(B):
def method1(self,):
do_something
def method2(self,):
do_something_else
为什么作者在自我后面留下逗号,他/她的目的是什么?
【问题讨论】:
标签: python
在我正在查看的代码中,我看到了一些这样的类方法:
class A(B):
def method1(self,):
do_something
def method2(self,):
do_something_else
为什么作者在自我后面留下逗号,他/她的目的是什么?
【问题讨论】:
标签: python
从语法上讲,结尾的逗号 is allowed 但实际上并没有任何意义。这几乎只是一种风格偏好。我认为大多数 python 程序员会放弃它(这也是我会给出的建议),但有些人可能更喜欢它,以便以后可以轻松添加更多参数。
您也可以keep it in there when calling the function。在使用大量默认参数的函数中,您会更频繁地看到这一点:
x = foo(
arg1=whatever,
arg2=something,
arg3=blatzimuffin,
)
这也适用于列表和元组:
lst = [x, y, z,]
tup = (x, y, z)
tup = x, # Don't even need parens for a tuple...
如果你想很好地格式化嵌套的东西,那就太好了:
{
"top": [
"foo",
"bar",
"baz",
],
"bottom": [
"qux",
],
}
在向列表中添加内容时,您只需要添加/编辑 1 行,而不是 2 行。
【讨论】: