【问题标题】:python class variable lookup by valuepython 类变量按值查找
【发布时间】: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'

我现在很高兴我不必担心性能。我想知道它为什么会这样:)

【问题讨论】:

标签: python performance variables dictionary static


【解决方案1】:

你的想法是正确的。字典不会每次都重新生成,只会在第一次创建时重新生成。查找是高效且可靠的,这不太可能导致我可以看到的问题。使用这种反向字典很常见,您也可以在一个好地方检查isinstance(value, Hashable)。你应该没事。

-- 已编辑--

你的代码很好,我只是错过了结尾的括号。

【讨论】:

    猜你喜欢
    • 2012-10-06
    • 2015-07-20
    • 1970-01-01
    • 2019-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-12
    • 2016-01-24
    相关资源
    最近更新 更多