【问题标题】:Python function will cycle through but error on the final iterationPython函数将循环通过,但在最后一次迭代时出错
【发布时间】:2015-11-13 05:49:07
【问题描述】:

在以下 Python 函数中,我使用 Python 2.7.6 和 SQLAlchemy 作为 ORM。我很困惑为什么即使函数循环通过,我仍然会收到以下错误。

def vacantShelter():
#Used to stay in bounds of the all the entries in the DB
shelterCount = session.query(Shelter).count
shelter_id = 1
print "Here are the Shelter results:"
while(shelter_id<=shelterCount):
    shelter = session.query(Shelter).filter(Shelter.id == shelter_id).first()
    if(shelter.max_capacity >= getShelterOccupancy(shelter_id)):
        print shelter.name + " has available space"
    else:
        print shelter.name + " is full! :("
    shelter_id = shelter_id + 1

让我感到困惑的是,考虑到有结果,它一开始运行正常,我不明白为什么在最后一次迭代中它会失败或如何处理它。

`Here are the Shelter results:
Oakland Animal Services has available space
San Francisco SPCA Mission Adoption Center is full! :(
Wonder Dog Rescue has available space
Humane Society of Alameda is full! :(
Palo Alto Humane Society is full! :(
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "pup_test.py", line 82, in vacantShelter
    if(shelter.max_capacity >= getShelterOccupancy(shelter_id)):
AttributeError: 'NoneType' object has no attribute 'max_capacity'`

【问题讨论】:

  • Shelter.id 值中是否存在 漏洞?例如,可能存在id 值为[1, 2, 3, 4, 5, 7] 的行。当你到达最后一个元素时,你会尝试找到一个id为6Shelter,但它并不存在。
  • 我在创建庇护所对象后添加了以下代码,我的错误不再存在:if not shelter: return 感谢@van 的提示。这是最有效的举措吗?
  • 由于我想展示的代码示例,我将添加一个答案。
  • 我认为这根本不是正确的举动,因为您的解决方案实际上会错过一些id最高的Shelters值。

标签: python-2.7 orm sqlalchemy


【解决方案1】:

此错误最可能的原因是Shelter.id 值中存在。例如,该表可能包含id 值为[1, 2, 3, 4, 5, 7] 的行。当您到达最后一个元素时,您将尝试查找 id 为 6 的 Shelter,但它不存在。

原则上,您的代码现在的工作方式是非常大胆地假设数据库中的所有行都具有从1 开始的连续id 值。但一般情况并非如此。相反,您可以直接迭代实例,而不是一个接一个地加载它们:

def vacantShelter():
    shelters = session.query(Shelter).all()
    for shelter in shelters:
        if(shelter.max_capacity >= getShelterOccupancy(shelter.id)):
            print shelter.name + " has available space"
        else:
            print shelter.name + " is full! :("

而且,它更干净。

【讨论】:

  • 感谢@van,这是有道理的。
  • 当然。如果您的getShelterOccupancy(...) 也可以在数据库端完成,您可能会在一个查询中执行所有逻辑
猜你喜欢
  • 1970-01-01
  • 2011-07-11
  • 2016-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多