How to reload class object method code in Python?

I found a way to reload the method of the class object at runtime, here is an example: First I define the class A, which lies on the file test.py.

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

then I run the Python shell on linux and execute the following code:

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

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

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

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

How do I write code to make an "a.Message" object to execute updated code.

Many thanks!

chu

+3
source share
3 answers

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

import test
reload(test)
from test import A

A, - A, , . , , , .

, IPython . , %reload ( ) %run .

+4

, , , . gist , , SO, :

, , , (.. ), . .

+1

, :

import sys
def update_class(instance):
  cls=instance.__class__
  modname=cls.__module__
  del sys.modules[modname]
  module=__import__(modname)
  instance.__class__=getattr(module,cls.__name__)

, , .

import sys

class ObjDebug(object):
  def __getattribute__(self,k):
    ga=object.__getattribute__
    sa=object.__setattr__
    cls=ga(self,'__class__')
    modname=cls.__module__ 
    mod=__import__(modname)
    del sys.modules[modname]
    reload(mod)
    sa(self,'__class__',getattr(mod,cls.__name__))
    return ga(self,k)

class A(ObjDebug):
   pass

a=A()

A, , a.

del sys.modules[modname] , None . ( )

0
source

Source: https://habr.com/ru/post/1784987/


All Articles