重载模块后在Python中的对象类型转换? [用于即时代码更改] [英] object type casting in Python after reloading a module? [for on-the-fly code changes]

查看:170
本文介绍了重载模块后在Python中的对象类型转换? [用于即时代码更改]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行一个交互式Python会话,它构建了 Python数据结构(5 GB以上),需要很长时间才能加载,所以我想利用 Python on (虽然有时,,而不必为此计划太多)。



我当前的问题如下:我有一个类的旧实例,我以后修改了代码并重新加载了模块 - 我想要老实例能够使用新的函数定义。我怎么做,而不只是手动将所有的信息从旧的实例复制到一个新的新实例?



这是我试过的。假设我有模块 M.py

 
def f(self):
printold class

是一个互动会话:

  import M 
old_a = Ma()

#假设现在我改变了源文件中MAF的定义]

reload(M)
#我尝试使用新的类定义与旧实例:
MAf(old_a )

此时,我从Python获得以下类型错误:



TypeError:未绑定的方法f()必须用A实例作为第一个参数来调用(获取A实例)

Python显然不高兴接收A的旧实例,即使它们基本上是功能等同的类型(在我的代码中) - 是否有任何方式'type cast'到新的实例类型,这样Python不会抱怨?道德上的东西: MAf((MA)old_a)

解决方案

在Python中没有投射,但您可以更改现有对象的类:这是完全合法的,并且完成工作:

  old_a .__ class __ = MA 
old_a.f()

只要你没有改变类方法和实例变量之间的关系,改变什么 __ init __ 或者这样的东西,这是完全精细。



编辑: jsbueno 指出: __ init __ 或在改变 __ class __ 时调用 __ new __ 方法。此外,在销毁时会调用新的 __ del __


I am running an interactive python session which builds big python data-structures (5+ GB) which take a long time to load, and so I want to exploit Python on-the-fly code change abilities at its maximum (though sometimes, without having to plan too much for that).

My current problem is the following: I have an old instance of a class that I have later modified the code and reloaded the module -- I would like the old instance to be able to use the new function definitions. How do I do that without just manually copying all the information from the old instance to a new fresh instance?

Here is what I have tried. Suppose I have the module M.py:

class A():
    def f(self):
        print "old class"

Here is an interactive session:

import M
old_a = M.a()

# [suppose now I change the definition of M.A.f in the source file]

reload(M)
# I attempt to use the new class definition with the old instance:
M.A.f(old_a)

at which point I get the following type error from Python:

TypeError: unbound method f() must be called with A instance as first argument (got A instance instead)

Python is obviously not happy to receive an old instance of A even though they are basically functionally equivalent types (in my code) -- is there any way I could 'type cast' it to the new instance type so that Python wouldn't complain? Something morally like: M.A.f( (M.A) old_a ) ?

解决方案

There is no casting in Python but you can change the class of an existing object: It is perfectly legal and does the job:

old_a.__class__=M.A
old_a.f()

As long as you haven't changed the relation between class methods and instance variables, changed what __init__ does or something like that this is perfectly fine.

EDIT: As jsbueno points out: The __init__ or __new__ methods are not called at the point of changing __class__. Further, the new __del__ will be called at destruction.

这篇关于重载模块后在Python中的对象类型转换? [用于即时代码更改]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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