【问题标题】:Python 3.8 class variable not persistentPython 3.8 类变量不是持久的
【发布时间】:2020-05-14 07:31:06
【问题描述】:

Python 类的类变量似乎不会在包之间持续存在。

我有一个“HookRegistry”类,它应该动态记录使用@regiser_hook 方法注释的函数。 IT 这样做很成功,但是当我再次查找已注册的挂钩列表时,保存它们的列表变量似乎已重新初始化。

class HookRegistry(object):
    hooks = []

    def register_hook(f):
        HookRegistry.hooks.append(f)
        print("Registrering hook. There are now {} hooks registered.".format(len(HookRegistry.hooks)))
        def wrap(*args, **kwargs):
            f(*args, **kwargs)
        return wrap

    def execute_hooks(*args, **kwargs):
        for f in HookRegistry.hooks:
            f(*args, **kwargs)

完整的源代码可以在https://github.com/conallprendergast/python_hook_registry_example/tree/not_working找到

我在 Arch linux 上运行 python 3.8

【问题讨论】:

  • 你如何确定它已经被重新初始化了?在您的示例代码中,实际的钩子执行将始终以 KeyError 终止(因为它试图从 kwargs 读取未传递的密钥)。另请注意:您的两个函数都应该用@staticmethod 装饰(或者应该删除无意义的类包装,因为它们实际上是全局函数)以明确它们根本不使用实例数据。
  • 你不需要包装器;只需返回fregister_hook 的重点不是为装饰函数添加功能,而只是更新列表。
  • @chepner:特别是考虑到他们忽略了return 来自f 的值,因此包装会破坏任何具有非None 返回值的函数。
  • @chepner:我指的是他们的实际示例代码,其中f 函数都接受**kwargs,但随后假设kwargs 包含密钥"day"
  • 啊,这不是问题所在。我忽略了这一点。

标签: python python-3.x python-decorators


【解决方案1】:

通过更改我的“挂钩”do_something* 文件中的代码来解决此问题。

的导入
from hookregistry import HookRegistry

需要改成

from .hookregistry import HookRegistry

【讨论】:

    【解决方案2】:

    这是行不通的,因为模块do_something* 没有执行。(我们很容易检查这一点:只需将不正确的代码添加到do_something.py

    这个可以修复,把这个代码加到hooks/__init__.py

    from .do_something import *
    from .do_something_else import *
    

    【讨论】:

    • 这些模块是从 init.py all 声明中导入的。向 do_something giles 添加语法错误的代码实际上会破坏代码
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-04
    • 1970-01-01
    • 2020-10-18
    • 2015-08-16
    • 2014-07-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多