python tips

How to create an enum in Python?
Use a function that dynamically creates a new class
def enum(**enums):
    return type('Enum', (object,), enums)
 
Numbers = enum(ONE=1, TWO=2, THREE=3)
 
assert Numbers.ONE == 1
assert Numbers.TWO == 2
assert Numbers.THREE == 3


Using a class
class Numbers(object):
    ONE = 1
    TWO = 2
    THREE = 3
 
assert Numbers.ONE == 1
assert Numbers.TWO == 2
assert Numbers.THREE == 3


How to test if a variable exists in Python?
try:
    print x
except NameError:
    x = 0
 
assert x == 0

你可能感兴趣的:(python)