Does Python import statement also import dependencies automatically?

前端 未结 2 2110
傲寒
傲寒 2020-12-19 05:28

I have the following file app.py

class Baz():
    def __init__(self, num):
        self.a = num
        print self.a

def foo(num):
    obj = Ba         


        
2条回答
  •  难免孤独
    2020-12-19 06:11

    Python does not automatically do any of these things.

    When you import something from a module (in this case, the app module), Python first runs all the code in the corresponding file (app.py). The code in the file app.py which you've written does two things:

    1. define the class Baz
    2. define the function foo

    When the function foo runs, Python looks for Baz in the module that foo is part of, and only there. (Well, it also checks local variables defined in the function foo, but you don't have any of those except obj.) Specifically, it looks for app.Baz. If you alter your main.py to do the same search:

    from app import foo
    foo(10)
    import app # same app that was already imported
    print app.Baz
    

    you will see that app.Baz is the class you defined in app.py.

    If you put the definition of class Baz in yet another file, and if you don't import that file, Python will not run it. This shows that Python does not automatically import dependencies. In particular, suppose app.py contains

    def foo(num):
        obj = Baz(num)
    

    and baz.py contains

    class Baz():
        def __init__(self, num):
            self.a = num
            print self.a
    

    and main.py is unchanged. You'll get an error because Python has not run the code to define the class Baz.

提交回复
热议问题