Python缩进错误:“预期缩进块”在Xcode中

1 投票
3 回答
16292 浏览
提问于 2025-04-17 16:24

我在使用Xcode和vi的时候遇到了一个错误。Python提示说,类LeastModel的那一行有一个缩进错误:期待一个缩进的代码块。我检查了Xcode的设置,选择了用4个空格来代替一个制表符,但我到处都在用制表符。请帮帮我!

def make_model(data,model):

class LeastModel():
    """
    linear system solved using linear least squares
    This class serves as an example that fulfills the model interface needed by the ransa function.
    """
    def __init__(self,input_columns,output_columns):
        self.input_columns = input_columns
        self.output_columns = output_columns
        #self.debug = debug

3 个回答

1

难道不应该是:

class LeastModel():
    """
    linear system solved using linear least squares
    This class serves as an example that fulfills the model interface needed by the ransa function.
    """
    def __init__(self,input_columns,output_columns):
        self.input_columns = input_columns
        self.output_columns = output_columns
        #self.debug = debug
2

假设你的代码没有复制错误,确实是这个样子,你需要把 __init__() 这个部分缩进,这样它才能在类的定义里面:

class LeastModel():
    """
    linear system solved using linear least squares
    This class serves as an example that fulfills the model interface needed by the ransa function.
    """
    def __init__(self,input_columns,output_columns):
        self.input_columns = input_columns
        self.output_columns = output_columns
        #self.debug = debug

补充:现在你已经提供了完整的代码,问题其实是你的 make_model() 函数下面什么都没有。如果这个函数真的应该什么都不做,那就在 def 这一行下面加上 pass(缩进一个级别)。如果不是这样的话,就在里面写点代码,或者直接把 def 这一行删掉。

5

你的问题是,在以下这行代码后面没有缩进的代码:

def make_model(data,model):

你可以选择:

  1. 删除那一行

  2. 在那个函数的主体里写一些缩进的代码

  3. 把整个类的定义缩进,这样你就可以在函数里面定义类 LeastModel 了。

根据你把函数命名为 make_model 和类命名为 LeastModel,我觉得你可能是想把类的定义放在这个函数里面。但是这可能是个错误——要注意,如果你在函数里面定义了这个类,你就不能在函数外面使用这个类(除非你用 return LeastModel 这一行把类返回出去)。

撰写回答