【问题标题】:Undefined name when using a function annotation使用函数注释时未定义的名称
【发布时间】:2015-02-04 01:43:38
【问题描述】:

我试图用hh:mm 来表达时间。我知道冒号告诉 python 从小时数到分钟数,但这不是我想要的。有人能解释一下纠正我这个错误的方法吗?

def extract_hours(hours:minutes):
    """returns an integer representing the number of hours number, number -> number"""
    return (hours)

这是我得到的错误:

NameError: name 'minutes' is not defined

【问题讨论】:

  • 你提议的函数是如何调用的?您似乎在尝试def hr(tm:'hours:minutes'): return int(tm.split(':')[0])
  • 是的,我必须将格式保持为“小时:分钟”,我尝试了您的解决方案,但它给了我冒号的语法错误...?

标签: python function python-3.x annotations


【解决方案1】:

Function annotations 必须是有效的expressions。这意味着,您不能在注释中使用未定义的名称,否则您将引发NameError

相反,您可以使用字符串文字:

def extract_hours(hours:'minutes'):

这是可行的,因为字符串文字是表达式。

【讨论】:

  • 我试过了,得到:TypeError: extract_minutes() 需要 1 个位置参数,但给出了 2 个
  • 那是调用者的问题,而不是定义的问题。当然,除非 extract_hours 实际上应该采用 两个 参数。在这种情况下,您需要使用, 而不是: 将其定义为def extract_hours(hours, minutes):
猜你喜欢
  • 2015-02-12
  • 1970-01-01
  • 2016-07-17
  • 2018-11-02
  • 1970-01-01
  • 2022-12-16
  • 2013-11-14
  • 2023-01-23
相关资源
最近更新 更多