【问题标题】:pass dict by reference to bit encoded list of functions通过引用位编码的函数列表传递 dict
【发布时间】:2013-06-21 21:48:31
【问题描述】:

我似乎对传递给函数列表(在子进程中)的Manager.dict() 有问题,因为当我在函数中修改它时,新值在外部不可用。 我创建了这样的函数列表:

gwfuncs = [reboot, flush_macs, flush_cache, new_gw, revert_gw, send_log]
gw_func_dict = dict((chr(2**i), gwfuncs[i]) for i in xrange(0,min(len(gwfuncs),8)))

然后这样称呼它:

for bit in gw_func_dict.keys():
    if gwupdate & ord(bit) == ord(bit):
        gw_func_dict[bit](fh, maclist)

现在假设我们正在谈论flush_macs(),无论我在maclist 函数中做什么,似乎都不会影响我函数之外的maclist - 为什么会这样?我如何修改它以使我的更改在外部可用?

【问题讨论】:

    标签: python dictionary multiprocessing pass-by-reference python-multiprocessing


    【解决方案1】:

    ==precedence& 高,所以你的if 语句实际上是这样的:

    if gwupdate & (ord(bit) == ord(bit)):
    

    添加一些括号就可以了:

    if (gwupdate & ord(bit)) == ord(bit):
    

    此外,您还可以稍微简化代码:

    gw_func_dict = dict((chr(2**i), func) for i, func in enumerate(gwfuncs[:8]))
    

    如果您使用的是 Python 2.7+:

    gw_func_dict = {chr(2**i): func for i, func in enumerate(gwfuncs[:8])}
    

    此外,默认情况下遍历字典会遍历其键,因此您可以从 for 循环中删除 .keys()

    for bit in gw_func_dict:
    

    【讨论】:

      猜你喜欢
      • 2015-02-24
      • 2023-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-25
      • 1970-01-01
      • 2020-10-02
      相关资源
      最近更新 更多