python类属性不在if条件中求值

2024-07-05 15:21:58 发布

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

我有一个python类如下

class Application(models.Model):
    name = models.CharField(help_text="Application's name",max_length=200)
    current_status = models.IntegerField(null=True, blank=True)
    class Meta:
        ordering = ["name"]

    @property
    def status(self):
        """Returns the current ApplicationStatus object of this Application."""
        try:
            return ApplicationStatus.objects.get(id = self.current_status)
        except ApplicationStatus.DoesNotExist as e:
            print e
            return None

在另一个类中,我检查属性状态,如下所示

^{pr2}$

虽然我确定应用程序的状态不是None,但是else print语句打印None,当我尝试访问状态时app.status.id应用程序状态,应用程序抛出异常NoneType has no property id。在

当我把条件改为:

^{3}$

它工作得很好。在

有人能告诉我为什么python属性没有在print语句中求值吗?在


Tags: nameselfnoneidtrue应用程序applicationmodels
3条回答

你这么说的应用程序状态通过了第一个if条件(所以不是None),但是当您打印它时,它不会打印任何。。。在

很清楚,第一次应用程序状态返回与“无”不同的值,第二次更改时返回应用程序状态(每次都对其求值)返回None

实际上,如果存储应用程序状态在另一个var中(因此它没有被修改),它工作得很好。。。在

我认为两次执行代码的原因是一样的:

试试这个测试:

print app.status
print app.status

第一次打印不是“无”,而是第二次“是”: 您必须查看两个调用之间的应用程序对象发生了什么变化(是否有信号等…) 尝试打印自身当前状态在status函数中。在

你说:

Although I am sure that the status of the application is not None, the else clause is executed

你发布的代码是:

if app.status is None:
        #do some thing
else:
        #do another thing

如果status不是None,那么将执行else子句。在

我不明白第二个case是如何工作的,因为else子句也应该在这里执行。在

相关问题 更多 >