[英]How to get all the attributes of a class as a list in python
I have the following class in Python. 我在Python中有以下课程。
class RULES(object):
TOTAL_REQUESTS = 'totalrequests'
HTML_SIZE = 'htmlsize'
JS_SIZE = 'jssize'
JS_COUNT = 'jscount'
DOMAIN_COUNT = 'domaincount'
REQ_PER_DOMAIN = 'reqperdomain'
DOMAIN_WITH_MAX_REQUESTS = 'domainwithmaxrequests'
IMAGE_SIZE = 'imagesize'
IMAGE_COUNT = 'imagecount'
HIGHEST_LATENCY_OBJECT = 'highestlatencyobject'
LARGEST_SIZE_OBJECT = 'largestsizeobject'
VARY_HEADER_OBJECTS = 'varyheaderobjects'
ERROR_RESPONSES = 'errorresponses'
COOKIE_REQUESTS = 'cookierequests'
TTFB_REQUESTS = 'ttfb_requests'
UNCACHED = 'uncached'
UNCOMPRESSED = 'uncompressed'
SPRITABLE = 'spritable'
MULTIPLE_REQUESTS = 'multiplerequests'
INLINABLE = 'inlinable'
NO_SERVER_CACHE = 'noservercache'
MORE_TTL = 'morettl'
MEDIAN_LOAD_TIME = 'median_load_time'
AVG_LOAD_TIME = 'avgloadtime'
DNS = 'dns'
HOST_TTL = 'host_ttl'
ORIGIN_TTL = 'origin_ttl'
THIRD_PARTY_HTTPS_REQ = 'thirdpartyhttpsreq'
Now I need to write a method to iterate over all the attributes and return them as a list. 现在,我需要编写一种方法来遍历所有属性并将它们作为列表返回。 I tried accessing individual attributes as
我尝试访问单个属性为
RULES.HOST_TTL
, but am nit sure how to iterate over them. RULES.HOST_TTL
,但是请确定如何遍历它们。 Is there a way in python to do that. python中有没有一种方法可以做到这一点。
You can also use class_name.__dict__
您也可以使用
class_name.__dict__
>>> class RULES(object):
... TOTAL_REQUESTS = 'totalrequests'
... HTML_SIZE = 'htmlsize'
... JS_SIZE = 'jssize'
... JS_COUNT = 'jscount'
... DOMAIN_COUNT = 'domaincount'
... REQ_PER_DOMAIN = 'reqperdomain'
... DOMAIN_WITH_MAX_REQUESTS = 'domainwithmaxrequests'
... IMAGE_SIZE = 'imagesize'
... IMAGE_COUNT = 'imagecount'
... HIGHEST_LATENCY_OBJECT = 'highestlatencyobject'
... LARGEST_SIZE_OBJECT = 'largestsizeobject'
... VARY_HEADER_OBJECTS = 'varyheaderobjects'
... ERROR_RESPONSES = 'errorresponses'
... COOKIE_REQUESTS = 'cookierequests'
... TTFB_REQUESTS = 'ttfb_requests'
... UNCACHED = 'uncached'
... UNCOMPRESSED = 'uncompressed'
... SPRITABLE = 'spritable'
... MULTIPLE_REQUESTS = 'multiplerequests'
... INLINABLE = 'inlinable'
... NO_SERVER_CACHE = 'noservercache'
... MORE_TTL = 'morettl'
... MEDIAN_LOAD_TIME = 'median_load_time'
... AVG_LOAD_TIME = 'avgloadtime'
... DNS = 'dns'
... HOST_TTL = 'host_ttl'
... ORIGIN_TTL = 'origin_ttl'
... THIRD_PARTY_HTTPS_REQ = 'thirdpartyhttpsreq'
...
>>> RULES.__dict__
dict_proxy({'REQ_PER_DOMAIN': 'reqperdomain', '__module__': '__main__', 'JS_COUNT': 'jscount', 'AVG_LOAD_TIME': 'avgloadtime', 'DOMAIN_WITH_MAX_REQUESTS': 'domainwithmaxrequests', 'UNCACHED': 'uncached', 'NO_SERVER_CACHE': 'noservercache', 'HOST_TTL': 'host_ttl', 'MULTIPLE_REQUESTS': 'multiplerequests', 'MORE_TTL': 'morettl', 'DNS': 'dns', 'SPRITABLE': 'spritable', '__dict__': <attribute '__dict__' of 'RULES' objects>, 'LARGEST_SIZE_OBJECT': 'largestsizeobject', 'TTFB_REQUESTS': 'ttfb_requests', 'TOTAL_REQUESTS': 'totalrequests', '__weakref__': <attribute '__weakref__' of 'RULES' objects>, 'ORIGIN_TTL': 'origin_ttl', 'VARY_HEADER_OBJECTS': 'varyheaderobjects', 'MEDIAN_LOAD_TIME': 'median_load_time', 'COOKIE_REQUESTS': 'cookierequests', 'DOMAIN_COUNT': 'domaincount', 'THIRD_PARTY_HTTPS_REQ': 'thirdpartyhttpsreq', 'HTML_SIZE': 'htmlsize', 'UNCOMPRESSED': 'uncompressed', 'HIGHEST_LATENCY_OBJECT': 'highestlatencyobject', 'INLINABLE': 'inlinable', 'ERROR_RESPONSES': 'errorresponses', 'IMAGE_SIZE': 'imagesize', 'JS_SIZE': 'jssize', 'IMAGE_COUNT': 'imagecount', '__doc__': None})
Filter 过滤
Variable names and values: 变量名称和值:
>>> { k:v for k,v in RULES.__dict__.iteritems() if not k.startswith('__') }
{'JS_COUNT': 'jscount', 'DOMAIN_WITH_MAX_REQUESTS': 'domainwithmaxrequests', 'UNCACHED': 'uncached', 'MULTIPLE_REQUESTS': 'multiplerequests', 'SPRITABLE': 'spritable', 'TTFB_REQUESTS': 'ttfb_requests', 'ORIGIN_TTL': 'origin_ttl', 'VARY_HEADER_OBJECTS': 'varyheaderobjects', 'MEDIAN_LOAD_TIME': 'median_load_time', 'HTML_SIZE': 'htmlsize', 'UNCOMPRESSED': 'uncompressed', 'ERROR_RESPONSES': 'errorresponses', 'IMAGE_SIZE': 'imagesize', 'AVG_LOAD_TIME': 'avgloadtime', 'REQ_PER_DOMAIN': 'reqperdomain', 'NO_SERVER_CACHE': 'noservercache', 'HOST_TTL': 'host_ttl', 'JS_SIZE': 'jssize', 'DNS': 'dns', 'LARGEST_SIZE_OBJECT': 'largestsizeobject', 'DOMAIN_COUNT': 'domaincount', 'TOTAL_REQUESTS': 'totalrequests', 'COOKIE_REQUESTS': 'cookierequests', 'IMAGE_COUNT': 'imagecount', 'MORE_TTL': 'morettl', 'HIGHEST_LATENCY_OBJECT': 'highestlatencyobject', 'INLINABLE': 'inlinable', 'THIRD_PARTY_HTTPS_REQ': 'thirdpartyhttpsreq'}
Variable names: 变量名:
>>> [ k for k,v in RULES.__dict__.iteritems() if not k.startswith('__') ]
['REQ_PER_DOMAIN', 'JS_COUNT', 'AVG_LOAD_TIME', 'DOMAIN_WITH_MAX_REQUESTS', 'UNCACHED', 'NO_SERVER_CACHE', 'HOST_TTL', 'MULTIPLE_REQUESTS', 'MORE_TTL', 'DNS', 'SPRITABLE', 'LARGEST_SIZE_OBJECT', 'TTFB_REQUESTS', 'TOTAL_REQUESTS', 'ORIGIN_TTL', 'VARY_HEADER_OBJECTS', 'MEDIAN_LOAD_TIME', 'COOKIE_REQUESTS', 'DOMAIN_COUNT', 'THIRD_PARTY_HTTPS_REQ', 'HTML_SIZE', 'UNCOMPRESSED', 'HIGHEST_LATENCY_OBJECT', 'INLINABLE', 'ERROR_RESPONSES', 'IMAGE_SIZE', 'JS_SIZE', 'IMAGE_COUNT']
Use the dir
function. 使用
dir
函数。 It'll likely give you more than what you're looking for, but you can filter it (eg only take ALL_CAPS words). 它可能会为您提供所需的内容,但您可以对其进行过滤(例如,仅输入ALL_CAPS个单词)。
Sample: 样品:
>>> class RULES(object):
... TOTAL_REQUESTS = 'totalrequests'
... HTML_SIZE = 'htmlsize'
... JS_SIZE = 'jssize'
... JS_COUNT = 'jscount'
... DOMAIN_COUNT = 'domaincount'
... REQ_PER_DOMAIN = 'reqperdomain'
... DOMAIN_WITH_MAX_REQUESTS = 'domainwithmaxrequests'
... IMAGE_SIZE = 'imagesize'
...
>>> import re
>>> all_caps = re.compile('^[A-Z_]+$')
>>> [attr for attr in dir(RULES) if all_caps.match(attr)]
['DOMAIN_COUNT', 'DOMAIN_WITH_MAX_REQUESTS', 'HTML_SIZE', 'IMAGE_SIZE', 'JS_COUNT', 'JS_SIZE', 'REQ_PER_DOMAIN', 'TOTAL_REQUESTS']
and once you have the name , it's easy to get value: 一旦有了名称 ,就很容易获得价值:
[getattr(RULES, attr) for attr in dir(fules) if all_caps.match(attr)]
Finally, if you're amenable to using a different type, you might be able to use an Enum here. 最后,如果您愿意使用其他类型,则可以在此处使用枚举 。
enum
wasn't added to the standard library until python3.4, but there are backports for python2.x. 直到python3.4才将
enum
添加到标准库中,但是python2.x有反向移植 。 I believe that your request would then look like: 我相信您的要求将如下所示:
class RULES(enum.Enum):
X = 'foo'
Y = 'bar'
# ...
for name, attr in RULES.__members__.items():
print(name, attr.value)
Try this: 尝试这个:
print dir(RULES)
print RULES.__dict__
First will give an List of the attributes of class including classes which it inherites. 首先将给出类属性的列表,包括它继承的类。 Second will give you an dictionary representation for the same
第二个将为您提供相同的字典表示
您可能需要查看类的__dir__
属性,该属性将类本身作为字典返回
You can use inspect
to get attribute name and value. 您可以使用
inspect
获取属性名称和值。
import inspect
all_attr = inspect.getmembers(RULES)
[attr for attr in all_attr if not(attr[0].startswith('__') and attr[0].endswith('__'))]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.