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
102 views
in Technique[技术] by (71.8m points)

python - Enum doesn't understand what I want to set it to

this probably seems a little obvious to you, and I'm sure once I figure it out I will feel pretty beat up myself. But for the life of me, I can't figure out what's wrong. My teacher used this strip of code to explain how enum's work, but he never ran it, and when I run it, I keep getting back a weird result. Here is the entire code below:

from enum import Enum

class Shape(Enum):
    SQUARE = 2
    DIAMOND = 1
    CIRCLE = 3
    ALIAS_FOR_SQUARE = 2

if Shape.SQUARE == Shape.DIAMOND:
    print("SQUARE == DIAMOND")
else:
    print("SQUARE != DIAMOND")

if Shape.SQUARE == 2:
    print("SQUARE == 2")
else:
    print("SQUARE != 2")

After I run everything through, the prints are as follows

SQUARE != DIAMOND (Expected)

SQUARE != 2 (Unexpected)

For some reason, it says square isn't two when I've triple checked that it was set to 2, and I don't see anywhere else that it would have been altered

question from:https://stackoverflow.com/questions/65911069/enum-doesnt-understand-what-i-want-to-set-it-to

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

1 Answer

0 votes
by (71.8m points)

Shape.SQUARE has type Shape while 2 has type int -- they are not equal. Do you want to use Shape.SQUARE.value?

from enum import Enum

Shape = Enum("Shape", "DIAMOND SQUARE CIRCLE")
if Shape.SQUARE.value == 2:
    print("Success")
else:
    print("Failure")

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

...