I have the following class:
class ExampleValue:
NULL = 'null'
BOOLEAN = 'true'
INTEGER = '4'
FLOAT = '?'
DECIMAL = '?'
STRING = '"HELLO"'
BYTES = 'b"xyz"'
DATE = 'DATE "2014-01-01"'
TIME = 'TIME "01:02:03"'
DATETIME = 'DATETIME "2014-01-01T01:02:03"'
INTERVAL = 'INTERVAL 4 HOUR'
GEOGRAPHY = 'POINT(1 1)'
JSON = 'JSON "[1,2,3]"'
STRUCT = '{"x": 2}'
ARRAY = '[1,2,3]'
And I would like to iterate from the first one to the last. Is there a way to do this while keeping the ordering (or should I use a different 'type' than a class?). How I am currently doing it is:
>>> for val in ExampleValue.__dict__: # or dir(ExampleValue)
... if not val.startswith('_'):
... print (val)
...
INTERVAL
STRING
DECIMAL
FLOAT
BYTES
DATETIME
STRUCT
JSON
BOOLEAN
TIME
DATE
INTEGER
ARRAY
NULL
GEOGRAPHY
CodePudding user response:
You can do this almost as-is, by just subclassing the enum
class. For example:
from enum import Enum
class ExampleValue(Enum):
NULL = 'null'
BOOLEAN = 'true'
INTEGER = '4'
FLOAT = '?'
DECIMAL = '?'
STRING = '"HELLO"'
BYTES = 'b"xyz"'
DATE = 'DATE "2014-01-01"'
TIME = 'TIME "01:02:03"'
DATETIME = 'DATETIME "2014-01-01T01:02:03"'
INTERVAL = 'INTERVAL 4 HOUR'
GEOGRAPHY = 'POINT(1 1)'
JSON = 'JSON "[1,2,3]"'
STRUCT = '{"x": 2}'
ARRAY = '[1,2,3]'
for val in ExampleValue:
print (val.name, val.value)
NULL null
BOOLEAN true
INTEGER 4
FLOAT ?
STRING "HELLO"
BYTES b"xyz"
DATE DATE "2014-01-01"
TIME TIME "01:02:03"
DATETIME DATETIME "2014-01-01T01:02:03"
INTERVAL INTERVAL 4 HOUR
GEOGRAPHY POINT (1 1)
JSON JSON "[1,2,3]"
STRUCT {"x": 2}
ARRAY [1,2,3]
The above works on python2.7
. As @Mark mentioned above according to Pep 520, the code in the question will work the same as the above on python3.6
and above.
CodePudding user response:
Maybe this can help:
class Example(object):
bool143 = True
bool2 = True
blah = False
foo = True
foobar2000 = False
example = Example()
members = [attr for attr in dir(example) if not callable(getattr(example, attr)) and not attr.startswith("__")]
print members