python class property does not evaluated in the if condition
I have a python class as follow
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开发者_JAVA百科."""
try:
return ApplicationStatus.objects.get(id = self.current_status)
except ApplicationStatus.DoesNotExist as e:
print e
return None
In another class I check the property status as in the following statements
app = Application()
if app.status is None:
#do some thing
else:
print app.status
Although I am sure that the status of the application is not None, the else print statement print None and when I try to access the status like app.status.id, the application throws an exception NoneType has no property id
.
When I changed the condition to:
app = Application()
st = app.status
if st is None:
#do some thing
else:
#do another thing
it works fine.
Can someone tell my why the python properties does not evaluated in the print statement?
You said:
Although I am sure that the status of the application is not None, the else clause is executed
The code you posted is:
if app.status is None:
#do some thing
else:
#do another thing
If the status
is not None
then the else clause will be executed.
What I can't understand if how the second case is working, since the else
clause should be executed here too.
you said that app.status passed the first if condition (so it's not None) but when you print it, it prints None...
that's clear, the first time app.status returns something different from None, the second time something changed and app.status ( wich is evaluated every time) returns None
in fact if you store the value returned by app.status in another var ( so it's not modified) it works fine...
I think the reason is that you are executing 2 times the same code but with a different context :
Try this test :
print app.status
print app.status
The first print should be not None, but the second yes : You have to look what changed into the Application object between the two call (do you have signals, etc...) Try to print self.current_status in the status function.
Maybe the problem is on the ApplicationStatus class.
In fact, what you're doing in the non working sample, is invoking "ApplicationStatus.objects.get(id = self.current_status)" twice. Probably, in the first time, it does return a valid value, and does change it's state, so in the second invocation, it does returns None (or throws an ApplicationStatus.DoesNotExist).
So, my suggestion: take a look at ApplicationStatus code.
精彩评论