【问题标题】:Using a function as dictionary key使用函数作为字典键
【发布时间】:2020-06-02 07:17:25
【问题描述】:

将函数用作字典键是否被认为是不好的形式?例如:

def add(a, b):
    return a + b

mydict = {add: "hello"}

【问题讨论】:

  • 你想在这里弄清楚什么???
  • add 不是函数的名称,它一个函数。 name 是字符串'add',也可以作为add.__qualname__ 访问。
  • 您希望解决的实际问题是什么? (你可能想用mydict做什么真的不是很明显。)
  • 我的问题纯属学术性的。只是想知道它是否被认为是不好的形式。允许这样做是 Python 的一个怪癖吗?
  • 取决于您的 实际 需要,它可能完全有效或相当奇怪。

标签: python


【解决方案1】:

是的,这是完全正确的。例如,您可以使用它来存储一个函数被调用次数的计数器:

def hi():
    print('hi')

funcs = {hi: 0}

print(funcs)
# {<function hi at 0x10fb39950>: 0}

for func in funcs:
    func()
    # hi
    funcs[func] += 1

print(funcs)
# {<function hi at 0x10fb39950>: 1}

【讨论】:

    【解决方案2】:

    函数通过function类的实例表示:

    >>> def f():
    ...   pass
    ...
    >>> f
    <function f at 0x000001D397363E18>
    >>> help(type(f))
    
    class function(object)
     |  function(code, globals[, name[, argdefs[, closure]]])
    

    所以函数类是从object类派生的,继承__hash__方法。 object 类中__hash__ 方法的默认实现使用rotating right 4 bitsid() 返回值计算哈希。 object的id()是内存地址。

    这就是函数获取哈希的方式。任何具有一些不可变状态的东西在技术上都可以具有哈希值。

    【讨论】:

      猜你喜欢
      • 2012-08-31
      • 1970-01-01
      • 2013-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-03
      相关资源
      最近更新 更多