how to reload a Class in python shell?

后端 未结 6 1865
既然无缘
既然无缘 2020-12-07 10:47

If I import a module defining a class of the same name belonging to a package, it is imported as a Class, not a Module because of the __init__.py of the parent package. See

6条回答
  •  长情又很酷
    2020-12-07 10:56

    I have one myfile.py file which contains one class MyClass

    To import just do:

    from myfile import MyClass
    mc = MyClass()
    

    To reload:

    import sys
    del sys.modules['myfile']
    from myfile import MyClass
    modifiedmc = MyClass()
    

    This is very useful while building modules. one can put these inside a function and just call the function

    def myreload():
       import sys
       del sys.modules['myfile']
       from myfile import MyClass
       modifiedmc = MyClass()
       global mc
       mc = modifiedmc
    

提交回复
热议问题