Use 'import module' or 'from module import'?

前端 未结 19 2132
一向
一向 2020-11-21 07:47

I\'ve tried to find a comprehensive guide on whether it is best to use import module or from module import. I\'ve just started with Python and I\'m

19条回答
  •  说谎
    说谎 (楼主)
    2020-11-21 08:17

    One of the significant difference I found out which surprisingly no-one has talked about is that using plain import you can access private variable and private functions from the imported module, which isn't possible with from-import statement.

    Code in image:

    setting.py

    public_variable = 42
    _private_variable = 141
    def public_function():
        print("I'm a public function! yay!")
    def _private_function():
        print("Ain't nobody accessing me from another module...usually")
    

    plain_importer.py

    import settings
    print (settings._private_variable)
    print (settings.public_variable)
    settings.public_function()
    settings._private_function()
    
    # Prints:
    # 141
    # 42
    # I'm a public function! yay!
    # Ain't nobody accessing me from another module...usually
    

    from_importer.py

    from settings import *
    #print (_private_variable) #doesn't work
    print (public_variable)
    public_function()
    #_private_function()   #doesn't work
    

提交回复
热议问题