Last active
July 31, 2019 09:15
-
-
Save jan-g/d067acb36d26c5ea3efbbb1b8805d3cc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from enum import IntFlag, auto | |
class Colour(IntFlag): | |
R = auto() # When the class is defined, this'll get the value 1 | |
G = auto() # ... and 2 | |
B = auto() # ... and 4, and so on | |
Cyan = G | B # You can construct combinations inside the class definition | |
def is_blue(self): | |
return (self & Colour.B) != 0 | |
# Colour instances behave a bit like integers (although they print differently) | |
# auto() is magic which causes the constants defined in the class to take on power-of-two values. | |
>>> colour.B == 4 | |
True | |
>>> Colour.R | |
<Colour.R: 1> | |
>>> Colour.G | |
<Colour.G: 2> | |
>>> Colour.B | |
<Colour.B: 4> | |
>>> Colour.Cyan | |
<Colour.Cyan: 6> # 6 = 4 | 2 | |
# You can use bitwise operations on their members | |
>>> c = Colour.R | Colour.B | |
>>> c | |
<Colour.B|R: 5> | |
# Then the is_blue method uses that fact to check if a particular bit is set | |
>>> c.is_blue() | |
True | |
>>> Colour.Cyan.is_blue() | |
True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment