In Python, how do you change an instantiated object after a reload?

前端 未结 7 1681
南方客
南方客 2021-02-04 06:25

Let\'s say you have an object that was instantiated from a class inside a module. Now, you reload that module. The next thing you\'d like to do is make that reload affect that c

7条回答
  •  旧巷少年郎
    2021-02-04 07:08

    You have to get the new class from the fresh module and assign it back to the instance.

    If you could trigger this operation anytime you use an instance with this mixin:

    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)
    

提交回复
热议问题