How to reload the code of a method of class object in Python?

后端 未结 4 2309
予麋鹿
予麋鹿 2020-12-20 00:24

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          


        
4条回答
  •  被撕碎了的回忆
    2020-12-20 01:00

    You have to reload your module from the fresh code, get the class and assign it back to the instance:

    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__)
    

    While developing and updating the code you could use the same trick to define instances that reload their class anytime they are used.

    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()
    

    If you edit the code of A to add a method, then you can use it without instantiating again a.

    Actually del sys.modules[modname] seems to create nasty bugs for which some symbols becomes None objects from one line to the other. (not understood why)

提交回复
热议问题