【问题标题】:Python Django check if an attribute exists or has been setPython Django 检查属性是否存在或已设置
【发布时间】:2013-04-21 04:40:44
【问题描述】:

我有一个 User 对象和一个 UserInfo 对象,它们具有一对一的关系。我只是添加了UserInfo 对象,所以一些用户已经拥有User 对象但没有UserInfo 对象。我想检查 User 对象是否有与之关联的 UserInfo 对象,如果没有,则将它们重定向到我可以获得一些信息的页面。我还是 python 的新手,并尝试做一个if request.user.user_info:,当它不存在时会引发异常,所以我最终这样做了:

 user = request.user
    try:
        user.user_info.university
    except:
        print 'redirect to info page'

这很好用,但我觉得异常应该是异常而不是 if 语句替代。有没有更好的方法来做到这一点?

【问题讨论】:

标签: python django


【解决方案1】:

我会说处理异常是pythonic方法。你可以这样做:

try:
    # do your thing when user.user_info exists
except AttributeError: # Be explicit with catching exceptions.
    # Redirect.

有一个名为it's easier to ask for forgiveness than permission (EAFP) 的编程概念在Python 中被广泛使用。我们假设给定对象存在属性、键等,并在它们不存在时捕获异常。

这里有一些关于 EAFP 的参考资料和 SO 问题。

Python glossary
What is the EAFP principle in Python
EAFP and what is really exceptional

【讨论】:

  • 也可以使用python hasattr()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-05-05
  • 2014-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-14
  • 2018-10-01
相关资源
最近更新 更多