Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
397 views
in Technique[技术] by (71.8m points)

class - How can I access an enum member with an input in python

I am trying to access the value of the enum variables with an input.

Here is my code:

class Animals(Enum):
    Dog = 1
    Cat = 2
    Cow = 3 

Choose = input('Choose an animal')

print(Animals.Choose.value)

Which gives me an error perhaps because Animals does not contain Choose.

How can I distinguish between a member in the enum and my input variable?

So that if I input Dog it would give 1 (the value of the Dog variable)?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can try using getattr:

from enum import Enum
class Animals(Enum):
    Dog = 1
    Cat = 2
    Cow = 3 


Choose = input('Choose an animal')

print(getattr(Animals, Choose).value)

Output:

1

getattr stands for "get attribute", which means it gets the variable in the class which it's name is what the second argument is.

Enums have already builtin __getitem__ methods, so you can directly index it with [] brackets, like this:

print(Animals[Choose].value)

Output:

1

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...