Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/heroku/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python缩进问题?_Python - Fatal编程技术网

Python缩进问题?

Python缩进问题?,python,Python,我对python很陌生。这是我第一次用python处理类。当我尝试运行此脚本时,我得到 缩进错误:应为缩进错误 挡块 这有什么问题 import random class Individual: alleles = (0,1) length = 5 string = "" def __init__(self): #some constructor work, here. def evaluate(self): #som

我对python很陌生。这是我第一次用python处理类。当我尝试运行此脚本时,我得到

缩进错误:应为缩进错误 挡块

这有什么问题

import random

class Individual:
    alleles = (0,1)
    length = 5
    string = ""

    def __init__(self):
        #some constructor work, here.

    def evaluate(self):
        #some stuff here.

    def mutate(self, gene):
        #mutate the given gene.

    def onePointCrossover(self, partner):
        #at some random point, crossover.

    def twoPointCrossover(self, partner):
        #at two random(?) points, crossover.

class World:
    def __init__(self):
        #stuff.

    def buildPopulation(self):
        #stuff.
        for individual in self.population():
            for i in range(0, individual.length):
                print random.random()


    def display(self):
        #print some output stuff.

if __name__ == '__main__':
    print "hi there"

所有这些方法都只包含一条注释

例如,要修复它,请执行以下操作

def twoPointCrossover(self, partner):
        #at two random(?) points, crossover.
        pass

注释不算作可编译语句,因此有一堆空块。这就是为什么它会给你缩进错误。

如果你使用的是以
结尾的东西:
需要缩进的块,而你没有任何要放在那里的东西(除了注释),那么你需要使用
pass

例如

更改:

class World:
    def __init__(self):
       #stuff.
致:


所有的方法都是如此。

除非你在这篇文章中缩写了你的代码,否则你需要在所有没有任何代码的函数之后通过
pass

def __init__(self):
    #stuff.
乍一看,这似乎是错误的。尝试将其更改为:

def __init__(self):
    #stuff.
    pass

当你只是概述你的类,并且有一堆什么都不做的方法时,你需要插入
pass
语句来表明什么都没有发生

像这样:

class Individual:
    alleles = (0,1)
    length = 5
    string = ""

    def __init__(self):
        #some constructor work, here.
        pass

    def evaluate(self):
        #some stuff here.
        pass
    ...

意外的缩进消息是因为python正在寻找一个缩进语句来遵循方法定义

仔细检查所有代码中的制表符和空格,确保没有混淆它们。包含多个空格的行可能与包含单个制表符的行相同。

其他行已经介绍了
pass
,因此我只想补充一点,对于python初学者来说,可能需要一些时间才能习惯空白的重要性


在习惯之前,您可能希望在保存文件时养成将制表符转换为空格或将空格转换为制表符的习惯。就我个人而言,我更喜欢使用制表符,因为如果按1关闭(特别是在嵌套块的开头/结尾),则更容易区分差异。

我认为为了这篇文章,他用注释替换了代码-也许不是。
def __init__(self):
    #stuff.
    pass
class Individual:
    alleles = (0,1)
    length = 5
    string = ""

    def __init__(self):
        #some constructor work, here.
        pass

    def evaluate(self):
        #some stuff here.
        pass
    ...