Discussion of Python modules

Four forms module

What is a module

A module is a py file, this file has a lot of functions py

  1. Custom modules, common.py called common modules
  2. Third-party modules: the need to install their own 130 000 third-party libraries, omnipotent, write library (made easier)
  3. Built-in module: python interpreter comes, no need to install
  4. Package -> File folder containing __inti__.py, a special module (solve a problem)

import和from......import

import import module for the first time three things happened:

  1. Create a module to module, whichever namespace

  2. Execution module corresponding file, will perform the namespace name generated in the process are thrown into the module

  3. Get a module name in the current executable file

from ... import ... first import module happened three things:

1. module to create whichever is the name of a space module
2. module corresponding executable file, the name of the implementation process modules produced are thrown into the namespace
3. get a name in the current namespace executable file, which name of a module directly to a name, which means you can not add any prefix directly

Circulation import

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

y = 'm1'
#在运行m1时会去m2中找x但在第二行时又会去m1中找y,这样就会造成死循环,并报错

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

x = 'm2'
#在运行m2时会去m1中找y但在第二行时又会去m2中找x,这样就会造成死循环,并报错


#解决方法

# 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'

The module search path

Module is actually a file, if you want to execute the file, first of all need to find the path to the module (a folder). If the module file path and execute files are not under the same file directory, we need to specify the module's path.

The module search path refers to when importing module needs to retrieve folder.

When import modules lookup module sequence is:

  1. Start with the memory module has been imported looking
  2. Built-in module
  3. Environment variable sys.path looking in

Two uses Python file

There are two uses python file a file is performed; the other is being introduced as a module.

Executable file: the file currently running executable file called

Module files: two uses .py file to run 05 Python files, m1 is the module file

Execute files and modules file is relative.

random module

import random

# 最常用的方法
print(random.random())  # 0-1的随机数

print(random.randint(0,100))  # 0-100的整数

lt = [1,2,3,4,5,]
random.shuffle(lt)  # 打乱容器类元素  --> 列表和字典
print(lt)

# 了解

print(random.randrange(1,10))  # 1,9之内的整数

print(random.uniform(1,3))  # 1-3的小数

print(random.choice([1,2,3,'a','b']))  # 选一个

print(random.sample([1,2,3,'a','b'],2))  # 选2个

Guess you like

Origin www.cnblogs.com/MrYang161/p/11359832.html