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

前端 未结 7 1598
南方客
南方客 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:14

    The following code does what you want, but please don't use it (at least not until you're very sure you're doing the right thing), I'm posting it for explanation purposes only.

    mymodule.py:

    class ClassChange():
        @classmethod
        def run(cls,instance):
            print 'one',id(instance)
    

    myexperiment.py:

    import mymodule
    
    myObject = mymodule.ClassChange()
    mymodule.ClassChange.run(myObject)
    
    # change mymodule.py here
    
    reload(mymodule)
    mymodule.ClassChange.run(myObject)
    

    When in your code you instanciate myObject, you get an instance of ClassChange. This instance has an instance method called run. The object keeps this instance method (for the reason explained by nosklo) even when reloading, because reloading only reloads the class ClassChange.

    In my code above, run is a class method. Class methods are always bound to and operate on the class, not the instance (which is why their first argument is usually called cls, not self). Wenn ClassChange is reloaded, so is this class method.

    You can see that I also pass the instance as an argument to work with the correct (same) instance of ClassChange. You can see that because the same object id is printed in both cases.

提交回复
热议问题