简体   繁体   中英

How to get sorted members in this class?

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

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]

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM