Python 使用函数注释时未定义的名称
我试图用Python 使用函数注释时未定义的名称,python,function,python-3.x,annotations,Python,Function,Python 3.x,Annotations,我试图用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
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 extract_hours(hours:'minutes'):
这是因为字符串文字是表达式。我试过了,得到了:TypeError:extract\u minutes()接受1个位置参数,但给出了2个。这是调用方的问题,而不是定义的问题。当然,除非extract\u hours
实际上应该包含两个参数。在这种情况下,您需要将其定义为def extract\u hours(hours,minutes):
带有,
而不是:
。建议的函数如何调用?您似乎想说defhr(tm:'hours:minutes'):return int(tm.split(':')[0])
是的,我必须保持格式为'hours:minutes',我尝试了您的解决方案,但它给了我冒号的语法错误。。。?