Python full-stack automated series Python Programming Fundamentals (modules and packages)

A module

1) the definition of

Module: Python module is a file, ending .py, containing Python object definitions and Python function
package: Python package is a directory containing a __init__.py file (folder)

2) effect module

  a. module lets you organize your Python code segments logically
  b. Place the code related function inside the module allows you to write a code with better, more understandable
  c. modules can be defined functions, variables, and classes, modules Lane also can contain executable code

important point:

  ① when introduced during module, the module will be executed again introduced from above

  ② When the module is introduced, introducing the same directory, PyCharm not possible to identify, will code marked red (does not mean error)

    Solution: From the project directory, an import down a

Second, the imported modules embodiment

1) Import Module

  import module name (note that you can not use import package name / folder )

2) introducing a variable or function module

  import module name from variables / functions (note, if the import function or variable together, separated by commas may be used )

3) from alias to import content import

  from import module as a function of a variable or an alias

  from folder folder import module as an alias

4) Not recommended

  module name from import * (import all variables and functions)

  from the folder. folder import * (all imported modules specified folder)

Third, Question 1: making imported modules when the module will be imported executed from the top down again, if part of the code do not want to perform when importing how to do?

  Question 2: What is inside the package __init__.py use?


Question 1: Can be magic variables (python built-in)

  __name__:  If you run the file directly (as if a startup file), then the file is __name__ "__main__"

  If the file (module) is introduced, then the value of the file on __name__ module name

  __file__: path represents the current file

Example:

FUNC DEF (): 
Print ( "Python ---- func01")
A = 100
Print ( "__ value of name__", __ name__)

# This condition will only be established when the direct running of this document, this time imported modules condition is not satisfied
IF __name__ == "__main__":
Print (a)
FUNC ()
Print ( "__ value of name__", __ name__)
Print ( "__ value of file__", __file__)

operation result:

 

Guess you like

Origin www.cnblogs.com/bluesea-zl/p/12209819.html