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

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

    I'm not sure if this is the best way to do it, or meshes with what you want to do... but this may work for you. If you want to change the behavior of a method, for all objects of a certain type... just use a function variable. For example:

    
    def default_behavior(the_object):
      print "one"
    
    def some_other_behavior(the_object):
      print "two"
    
    class Foo(object):
      # Class variable: a function that has the behavior
      # (Takes an instance of a Foo as argument)
      behavior = default_behavior
    
      def __init__(self):
        print "Foo initialized"
    
      def method_that_changes_behavior(self):
        Foo.behavior(self)
    
    if __name__ == "__main__":
      foo = Foo()
      foo.method_that_changes_behavior() # prints "one"
      Foo.behavior = some_other_behavior
      foo.method_that_changes_behavior() # prints "two"
    
      # OUTPUT
      # Foo initialized
      # one
      # two
    

    You can now have a class that is responsible for reloading modules, and after reloading, setting Foo.behavior to something new. I tried out this code. It works fine :-).

    Does this work for you?

提交回复
热议问题