Python-day16 (formal learning)

Keywords: Python less Mac Pycharm

Catalog

Modular

What is a module?

Modules are the aggregation of a series of functions, while functions are the aggregation of a certain function, so modules can be regarded as the aggregation of a bunch of functions. A py file can contain a bunch of functions, so a py file can be considered as a module. If the file name of the PY file is module.py, the module name is module.

Four Forms of Modules

In Python, there are four types of modules:

  1. Custom Module: If you write a py file yourself and write a bunch of functions in it, it's called a custom module, even if it's written in python.
  2. Third-party modules: C or C++ extensions that have been compiled into shared libraries or DLL s
  3. Built-in module: Built-in module written in C and linked to python interpreter
  4. Packet: A folder that organizes a series of modules together.

Why use modules

  1. Using third-party or built-in modules is a kind of usage doctrine, which can greatly improve the efficiency of development.
  2. Custom module, which writes the common functions used in our own program into a python file, and then the components of the program can refer to the functions of the custom module by importing.

How to use modules

Usually we use import and import from...import... import modules.

import

# run.py
import spam  # from the spam.py
import spam

Three things happened to the import first import module:

  1. Create a module namespace based on modules
  2. The file corresponding to the execution module drops all the names generated during execution into the module's namespace
  3. Get a module name in the current execution file

Repeated imports of modules create good results before they are directly consumed, and do not repeat the execution of module files, that is, repeated imports occur: spam=spam = memory address of module namespace

# run.py
import spam as sm


money = 111111

sm.money
sm.read1()  # 'spam module: 1000'
sm.read2
sm.change()

print(money)  # 1000

Import multiple modules

import spam, time, os

# The following methods are recommended
import spam
import time
import os

from...import...

# run.py

from spam import money

money = 10

print(money)  # 10

from...import... Three things happened to the first import module:

  1. Create a module namespace based on modules
  2. The file corresponding to the execution module drops all the names generated during execution into the module's namespace
  3. Get a name in the namespace of the current execution file that points directly to a name in the module, meaning that it can be used directly without any prefix
  • Advantages: No prefix, more concise code
  • Disadvantage: Easy to conflict with names in the namespace of the current execution file

Import all the functions in the file:

# spam.py

__all__ = ['money', 'read1']  # Only'money'and'read1' are allowed to be imported
# run.py
from spam import *  # Importing all functions in spam.py is limited to _all__

similarities and differences

Similarities:

  1. Both execute the file corresponding to the module, and both generate the module's namespace
  2. When they call functions, they need to run to the definition to find the scope relationship, regardless of the location of the call.

Difference

  1. Import needs to be prefixed; from...import... does not need to be prefixed

Cyclic Import Problem

# m1.py
print('from m1.py')
from m2 import x

y = 'm1'
  1. Create a namespace for m2
  2. Execute m2.py, dropping the name generated by execution to m2.py
  3. Get m2.x in the current execution file
# m2.py
print('from m2.py')
from m1 import y

x = 'm2'
  1. Create a namespace for m1
  2. Execute m1.py, dropping the name generated by execution to m1.py
  3. Get m1.y in the current execution file
# run.py
import m1
  1. Create a namespace for m1
  2. Execute m1.py, dropping the name generated by execution to m1.py
  3. Get m1 in the current execution file
  • If run.py is run, ImportError: cannot import name'y'
  • If m1.py is run, ImportError: cannot import name'x'
  • If m2.py is run, ImportError: cannot import name'y'

Solution

1.

# m1.py
print('from m1.py')


def func1():
    from m2 import x
    print(x)


y = 'm1'
# m2.py
print('from m2.py')

def func1():
    from m1 import y
    print(y)


x = 'm2'

2.

# m1.py
print('from m1.py')


y = 'm1'
from m2 import x
# m2.py
print('from m2.py')

x = 'm2'
from m1 import y

Module Search Path

A module is actually a file. If you want to execute a file, you first need to find the path of the module (a folder). If the module's file path and execution file are not in the same file directory, we need to specify the module's path.

The search path of the module refers to the folder that needs to be retrieved when importing the module.

The order of module lookup when importing module is:

  1. Look first for modules that have been imported from memory
  2. Built-in modules
  3. Custom Module
  4. Find the environment variable sys.path
import sys
print(f"sys.path: {sys.path}")

'''
['/Users/mac/Desktop/video/python/day16', 
'/Users/mac/Desktop/video/python', 
'/Applications/anaconda3/lib/python36.zip', 
'/Applications/anaconda3/lib/python3.6', 
'/Applications/anaconda3/lib/python3.6/lib-dynload', 
'/Applications/anaconda3/lib/python3.6/site-packages', 
'/Applications/PyCharm.app/Contents/helpers/pycharm_matplotlib_backend']
'''

Emphasis: The first value of sys.path is the folder where the current execution file is located

random module

import random
# Decimals greater than 0 and less than 1
print(random.random())
0.42866657593385415
# Integers greater than or equal to 1 and less than or equal to 3
print(random.randint(1, 3))
3
# Integers greater than or equal to 1 and less than 3
print(random.randrange(1, 3))
2
# Decimals greater than 1 and less than 3, such as 1.927109612082716
print(random.uniform(1, 3))
2.1789596280319605
# Any element in the list, i.e.'1'or'23' or [4,5]
print(random.choice([1, '23', [4, 5]]))
[4, 5]
# random.sample([], n), a combination of any n elements of a list element, example n=2
print(random.sample([1, '23', [4, 5]], 2))
['23', 1]
lis = [1, 3, 5, 7, 9]
# To disrupt the order of l is equivalent to shuffling.
random.shuffle(lis)
print(lis)
[9, 1, 5, 7, 3]

Posted by buraks78 on Thu, 15 Aug 2019 01:46:23 -0700