[英]How to get sorted members in this class?
I have the following class:我有以下 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?).有没有办法在保持订购的同时做到这一点(或者我应该使用与 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.您几乎可以按原样执行此操作,只需将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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.