如何在Python中重新加载类对象方法的代码? [英] How to reload the code of a method of class object in Python?

查看:423
本文介绍了如何在Python中重新加载类对象方法的代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找到了一种在运行时重新加载类对象的方法的方法,下面是示例: 我首先定义了一个类A,它位于文件test.py中.

I'm find a way to reload the method of a class object at runtime,here is the example: I have define a class A firstly which lies on the file test.py.

class A:
    def __init_(self):
        pass
    def Message(self):
        print "1"

然后我在linux中启动Python shell,并执行以下代码:

then I start Python shell in the linux, and execute the following code:

>>> from test import A
>>> a = A()
>>> a.Message()
1

现在,我即时运行了test.py,并更改了消息"方法:

Now I vi the test.py in the fly, and change the method "Message":

class A:
    def __init_(self):
        pass
    def Message(self):
        print "2"

但是当我在Python shell中执行a.Message()时,结果始终是"1" 而不是"2"

but when I execute the a.Message() in the Python shell, the result is always the "1" and not "2"

我如何编写代码以使对象"a.Message"执行更新后的代码.

How I write the code to make the object 'a.Message' to execute the updated code.

非常感谢!

chu

推荐答案

要在交互式解释器中重新发布您的模块,可以使用

To relaod your module in the interactive interpreter, you can use

import test
reload(test)
from test import A

但这不会影响已经存在的A实例-它们仍将是旧类型A,因此具有旧方法.我认为不可能更改现有实例,也不是一个好主意.

But this won't affect instance of A which already exist -- they will still be of the old type A, hence having the old method. I think it is not possible to change existing instances, nor do I think it is a good idea.

顺便说一句,我建议使用 IPython 进行代码测试.使用%reload魔术和(甚至更有用的)%run魔术来测试模块,它有助于递归重新加载.

By the way, I would recommend using IPython for code testing. It facilitates recursive reload using the %reload magic, and (even more useful) the %run magic to test modules.

这篇关于如何在Python中重新加载类对象方法的代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆