不带缩进的Python def

2024-09-22 16:31:59 发布

您现在位置:Python中文网/ 问答频道 /正文

在我拥有的源文件中,以下格式多次出现(注意def行后没有缩进):

def sendSystemParms2(self, destAddress, subid, state):

raw = sysparms_format2.build(Container(
length = 0x0D,
command = MT_APP_MSG_CMD0))

def method2(parm2):
print parm2

它在运转。我很困惑。有什么提示吗? 我不能上传图片,因为我是新的,没有足够的声誉,但我可以显示证据。在


Tags: buildselfrawcontainerdef格式state源文件
1条回答
网友
1楼 · 发布于 2024-09-22 16:31:59

您有一个混合使用制表符和空格的文件。在

Python将tabs扩展到8个空格,但您在编辑器中查看的文件使用的tabstop size为four spaces。在

函数体使用制表符进行缩进,但是def行使用4个空格。就Python而言,方法体是正确缩进的。在

如果我将文本编辑器设置为使用大小为8个空格的制表符,然后选择文本以使编辑器突出显示选项卡,我会看到:

source code with indentation highlighted

这些线表示制表符。在

这是您根本不应该使用制表符进行缩进的原因之一。Python style guide建议只使用空格进行缩进。在Python3中,像这样混合制表符和空格是一个语法错误。在

您可以告诉python2也为这种制表符和空格的组合使用TabError,方法是使用^{} command line switch运行Python:

-t
Issue a warning when a source file mixes tabs and spaces for indentation in a way that makes it depend on the worth of a tab expressed in spaces. Issue an error when the option is given twice (-tt).

相关问题 更多 >