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

前端 未结 19 2128
一向
一向 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:10

    Since I am also a beginner, I will be trying to explain this in a simple way: In Python, we have three types of import statements which are:

    1. Generic imports:

    import math
    

    this type of import is my personal favorite, the only downside to this import technique is that if you need use any module's function you must use the following syntax:

    math.sqrt(4)
    

    of course, it increases the typing effort but as a beginner, it will help you to keep track of module and function associated with it, (a good text editor will reduce the typing effort significantly and is recommended).

    Typing effort can be further reduced by using this import statement:

    import math as m
    

    now, instead of using math.sqrt() you can use m.sqrt().

    2. Function imports:

    from math import sqrt
    

    this type of import is best suited if your code only needs to access single or few functions from the module, but for using any new item from the module you have to update import statement.

    3. Universal imports:

    from math import * 
    

    Although it reduces typing effort significantly but is not recommended because it will fill your code with various functions from the module and their name could conflict with the name of user-defined functions. example:

    If you have a function of your very own named sqrt and you import math, your function is safe: there is your sqrt and there is math.sqrt. If you do from math import *, however, you have a problem: namely, two different functions with the exact same name. Source: Codecademy

提交回复
热议问题