Python 2枚举Examp

2024-04-30 03:58:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我找到了这段代码,它应该说明枚举是如何工作的。我知道现在在Python3中情况有所不同,但我想理解这个示例。我需要输入什么才能执行print("You chose the easy option")

我试过1EasyChoice.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!")

Tags: the代码youeasyenummediumoptionenums
3条回答

这不起作用,因为您正在比较字符串和整数。您可以将输入作为整数

choice = int(input("Enter choice: "))

该示例并没有创建枚举,只是创建了一个包含一些具有整数值的成员的类

它在Python3中不起作用的原因是因为在Python2中input()eval编辑了输入的内容,所以键入1实际上返回了一个int;在python3中input与python2的raw_input()相同,后者返回str并使您进行任何必要的转换

换句话说:

  • Python2
    >>> input('give me a number: ')
    give me a number:                # enter '1' and hit <Enter>
    1                                # returns the int 1
  • Python3
    >>> input('give me a number: ')
    give me a number:                # enter '1' and hit <Enter>
    '1'                              # returns the str '1'

对于实际的Enum,请使用stdlib enum模块或第三方^{}1模块(该模块支持高级Enum创建并支持Python 2)

实际的Enum如下所示:

from enum import Enum          # or from aenum import Enum

class Choice(Enum):
    Easy = 1
    Medium = 2
    Hard = 3

以及转换用户输入:

choice = input("Enter choice: ")
choice = Choice(int(choice))

if choice is Choice.Easy:        # NB: use `is` instead of `==` for normal enums
    ...

披露:我是Python stdlib ^{}^{} backportAdvanced Enumeration (^{})库的作者

用户输入的输入是字符串类型,在选项中是整数。 进行更改:

Choice = enum(Easy = '1', Medium = '2', Hard = '3')

或者

choice = int(input("Enter choice: "))

在这种情况下,您需要处理异常valueError

相关问题 更多 >