【发布时间】:2012-04-11 23:47:30
【问题描述】:
我有一个带有静态变量的类,用于查找错误/状态代码。 以HTTP状态码为例
class Foo(object):
OK = 200
Not_Modified = 304
Forbidden = 403
Internal_Server_Error = 500
现在我需要根据代码(200、403 等)检索口头状态(“OK”、“Not_Modified”等)。我不能修改类的结构,因为其他程序正在使用它。所以我创建了一个字典description_by_val,其中包含{code : description}:
from collections import Hashable
class Foo(object):
OK = 200
Not_Modified = 304
Forbidden = 403
Internal_Server_Error = 500
description_by_val = dict((value, key)
for key, value in locals().iteritems()
if not key.startswith("__") and value and isinstance(value, Hashable))
>>> Foo.description_by_val[200]
'OK'
现在我在性能和代码实践方面有疑问。
- 每次我调用
Foo.description_by_val都会导致字典重新生成吗?即使数据集非常小,这也不好,因为这会被调用数百万次。 - 这种方法只是不好的做法吗?我不想手动手动创建字典,我认为它应该是一个静态变量。
有什么想法吗?
更新:
我的同事刚刚向我指出,我可以在创建description_by_val 的过程中打印一些东西,看看它是否会重新生成。
>>> from collections import Hashable
>>>
>>> def show(key):
... print key
... return True
...
>>>
>>> class Foo(object):
... OK = 200
... Not_Modified = 304
... Forbidden = 403
... Internal_Server_Error = 500
... description_by_val = dict((value, key)
... for key, value in locals().iteritems()
... if not key.startswith("__") and key and isinstance(value, Hashable) and show(key))
...
OK
Forbidden
Internal_Server_Error
Not_Modified
>>>
>>> Foo.description_by_val
{200: 'OK', 304: 'Not_Modified', 403: 'Forbidden', 500: 'Internal_Server_Error'}
>>> Foo.description_by_val
{200: 'OK', 304: 'Not_Modified', 403: 'Forbidden', 500: 'Internal_Server_Error'}
>>> Foo.description_by_val[200]
'OK'
我现在很高兴我不必担心性能。我想知道它为什么会这样:)
【问题讨论】:
-
只要确保在所有状态之后创建
dict。 -
可能对这个问题的一些答案感兴趣:stackoverflow.com/questions/36932/…
标签: python performance variables dictionary static