我找到了这段代码,它应该说明枚举是如何工作的。我知道现在在Python3中情况有所不同,但我想理解这个示例。我需要输入什么才能执行print("You chose the easy option")
我试过1
、Easy
和Choice.Easy
到目前为止都没有成功
def enum(**enums):
return type('Enum', (), enums)
Choice = enum(Easy = 1, Medium = 2, Hard = 3)
choice = input("Enter choice: ")
if choice == Choice.Easy:
print("You chose the easy option")
elif choice == Choice.Medium:
print("You chose the medium option")
elif choice == Choice.Hard:
print("You chose the hard option")
else:
print("You should choose one of the three levels!")
这不起作用,因为您正在比较字符串和整数。您可以将输入作为整数
该示例并没有创建枚举,只是创建了一个包含一些具有整数值的成员的类
它在Python3中不起作用的原因是因为在Python2中
input()
eval
编辑了输入的内容,所以键入1
实际上返回了一个int
;在python3中input
与python2的raw_input()
相同,后者返回str
并使您进行任何必要的转换换句话说:
对于实际的} 1模块(该模块支持高级
Enum
,请使用stdlibenum
模块或第三方^{Enum
创建并支持Python 2)实际的
Enum
如下所示:以及转换用户输入:
披露:我是Python stdlib ^{} 、^{} backport 和Advanced Enumeration (^{}) 库的作者
用户输入的输入是字符串类型,在选项中是整数。 进行更改:
或者
在这种情况下,您需要处理异常valueError
相关问题 更多 >
编程相关推荐