意外的缩进错误,但缩进看起来正确



我一直在尝试运行这段代码,但它引发了一个缩进错误。无论我尝试什么,结果都是一样的。

如果我删除def __str__(self):之前的缩进和代码的其余部分,它可以正常工作,但在输出时,它显示的不是问题,而是"问题对象"。

def __str__(self):
^
IndentationError: unexpected indent

这是代码:

from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils import timezone
class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
    def __str__(self):
        return self.question_text
    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE) 
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)
    def __str__(self):
        return self.choice_text

我猜您是在混合空格和制表符。。。。

您可以使用autostep 缩进代码

请看https://pypi.python.org/pypi/autopep8

您正在混合空格和制表符。假设你文章中的代码使用的缩进字符与你在现实中使用的相同,下面是你的代码实际缩进的方式,>---表示一个选项卡,.表示一个空格。

from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils import timezone
class Question(models.Model):
....question_text = models.CharField(max_length=200)
....pub_date = models.DateTimeField('date published')
>---def __str__(self):
....>---return self.question_text
....def was_published_recently(self):
>---....return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
class Choice(models.Model):
....question = models.ForeignKey(Question, on_delete=models.CASCADE) 
....choice_text = models.CharField(max_length=200)
....votes = models.IntegerField(default=0)
>---def __str__(self):
....>---return self.choice_text

正如您所看到的,您的缩进是不一致的。当定义__str__()的两个实例时,现有的缩进级别是4个空格,但函数定义缩进了1个制表符。这会导致错误。

按照惯例,Python代码应该只使用空格缩进,而不是制表符,正是出于这个原因。

另请参阅PEP 8,特别是"缩进"one_answers"制表符或空格?"

最新更新