我正在寻找一种返回的方式 True 或字符串,然后使用该信息显示或不显示某些信息。这是我的代码:

def time_remaining(self):
    timer = self.timer
    now = datetime.datetime.utcnow().replace(tzinfo=utc)
    if timer < now:
        return True
    else:
        #Returns a timedelta in string
        return game_logic.timedelta_format(timer - now)

然后稍后我使用:

if time_remaining():
    possible = True
else:
    possible = False

return render(request, 'training.html',{'possible': possible})

最后在我的模板中:

{% if possible %}
    <some html>
{% else %}
    <different html>
{% endif %}

不知何故,即使time_reming返回字符串而不是true,我也总是会在

如何解决此问题?

有帮助吗?

解决方案

在Python中,非空字符串也评估为 True:

>>> bool('foo')
True
>>> bool('')
False

所以不管你是什么 time_remaining 功能返回,它将始终评估为 True 在你的 if 陈述。

您可能想使用类似的东西:

time_remaining() == True

甚至还有 time_remaining 返回 False 或者 None 如果没有时间(特别是如果您只使用输出 time_remaining 在你的 if 陈述)。

其他提示

time_remaining() == True:

似乎可以解决问题:)弄清楚它总是返回某些解释,确切地发生了什么

您的 time_remaining 函数始终返回一个评估的值 True 在里面 if 陈述。所以 possible 将一直是 True.

在第二个代码块中添加一些额外的逻辑以执行您期望的行为,例如测试时间增量的值。

函数输出应为相同的类型,并具有特殊值“无”来说明一个空输出(尽管我找不到此语句的任何引用...)。

因此,您应该这样做:

if timer < now:
    return game_logic.timedelta_format(empty_timedelta) 
else:
    #Returns a timedelta in string
    return game_logic.timedelta_format(timer - now)

或者:

time_limit = min(timer, now) #if 'min' applies
return game_logic.timedelta_format(timer - time_limit ) 

或者:

if timer < now:
    return None
else:
    #Returns a timedelta in string
    return game_logic.timedelta_format(timer - now)

或返回几个值:第一个说明结果的种类,第二个是实际结果

if timer < now:
    return (True, None)
else:
    #Returns a timedelta in string
    return (False, game_logic.timedelta_format(timer - now))
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top