class 是Python中的保留字,因此您应为参数选择其他名称,例如, cls 。另外,我不确定这是你的代码中的真正问题还是只是复制粘贴到SO的问题,引用字符是 ' 不是 鈥榎r 。如果我们把它们放在一起,这段代码应该正常工作:
class
cls
'
鈥榎r
def speed(cls): if (cls == 'secondary' or cls == 'tertiary' or cls == 'trunk' or cls == 'motorway' or cls == 'primary'): return 70 elif (cls == 'secondary_link' or cls == 'tertiary_link' or cls == 'trunk_link' or cls == 'motorway_link' or cls == 'primary_link'): return 45 elif (cls == 'service' or cls == 'track_grade1' or cls == 'track_grade2' or cls == 'track_grade3' or cls == 'track_grade4' or cls == 'track_grade5'): return 15 else: return 30
你可能想要这个:
def speed(aClass): if (aClass == 'secondary' or aClass == 'tertiary' or aClass == 'trunk' or aClass == 'motorway' or aClass == 'primary'): return 70 elif (aClass == 'secondary_link' or aClass == 'tertiary_link' or aClass == 'trunk_link' or aClass == 'motorway_link' or aClass == 'primary_link'): return 45 elif (aClass == 'service' or aClass == 'track_grade1' or aClass == 'track_grade2' or aClass == 'track_grade3' or aClass == 'track_grade4' or aClass == 'track_grade5'): return 15 else: return 30 fclass = 'tertiary_link' print(speed(fclass))
但在Python中更优雅:
def speed(aClass): if aClass in ['secondary', 'tertiary', 'trunk', 'motorway', 'primary']: return 70 if aClass in ['secondary_link', 'tertiary_link', 'trunk_link', 'motorway_link', 'primary_link']: return 45 if aClass in ['service', 'track_grade1', 'track_grade2', 'track_grade3', 'track_grade4', 'track_grade5']: return 15 else: return 30 fclass = 'tertiary_link' # Only for testing print(speed(fclass))
请注意 elif 我用了 if 因为每个分支都返回一个值(所以跳过下一个语句)。
elif
if