中动态重新加载类定义

中动态重新加载类定义

本文介绍了在 Python 中动态重新加载类定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用 Twisted 编写了一个 IRC 机器人,现在我已经到了想要能够动态重新加载功能的地步.

I've written an IRC bot using Twisted and now I've gotten to the point where I want to be able to dynamically reload functionality.

在我的主程序中,我执行 from bots.google import GoogleBot 并研究了如何使用 reload 重新加载 模块,但我仍然不知道如何动态重新导入类.

In my main program, I do from bots.google import GoogleBot and I've looked at how to use reload to reload modules, but I still can't figure out how to do dynamic re-importing of classes.

那么,给定一个 Python class,我如何动态地重新加载类定义?

So, given a Python class, how do I dynamically reload the class definition?

推荐答案

我想通了,这是我使用的代码:

I figured it out, here's the code I use:

def reimport_class(self, cls):
    """
    Reload and reimport class "cls".  Return the new definition of the class.
    """

    # Get the fully qualified name of the class.
    from twisted.python import reflect
    full_path = reflect.qual(cls)

    # Naively parse the module name and class name.
    # Can be done much better...
    match = re.match(r'(.*)\.([^\.]+)', full_path)
    module_name = match.group(1)
    class_name = match.group(2)

    # This is where the good stuff happens.
    mod = __import__(module_name, fromlist=[class_name])
    reload(mod)

    # The (reloaded definition of the) class itself is returned.
    return getattr(mod, class_name)

这篇关于在 Python 中动态重新加载类定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 16:01