程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

[Python] Python module foundation

編輯:Python

One 、 modular

It can be regarded as a collection of functions .

One py You can put a bunch of functions inside the file , So a py The file can be seen as a module .

If this py The file name of the file is module.py, The module name is module.

1、 Four forms of modules

stay Python in , There are four types of modules :

Custom module : If you write one yourself py file , Write a bunch of functions in the file , It's called a custom module , That is to use python Compiling .py file

Third-party module : Has been compiled as a shared library or DLL Of C or C++ Expand , Such as requests

Built-in module : Use C Write and link to python The built-in modules of the interpreter , Such as time

package ( Folder ): A folder that organizes a series of modules ( notes : There's one under the folder init.py file , This folder is called a package )

2、 Why use modules ?

Using third-party or built-in modules is a kind of fetching doctrine , It can greatly improve the development efficiency .

Custom module , The common functions we use in our own programs , Write a python file , Then each component of the program can refer to the function of the custom module by importing .

Two 、 How to use modules

Generally we use import and from...import... The import module .

As follows spam.py For example, the file code in .

# spam.py print('from the spam.py') money = 1000 def read1(): print('spam modular :', money) def read2(): print('spam modular ') read1() def change(): global money money = 0

1、import Module name

The grammar is as follows :

import module1[, module2[,... moduleN]

import Imported modules , Access needs to be prefixed .

import The first import of the module happened 3 thing :

Create a module namespace based on the module

File corresponding to the execution module , Throw all the names generated during execution into the module's namespace

Get a module name in the current execution file

Be careful : The repeated import of modules will directly reference the previously created results , The module's files will not be executed repeatedly .

# run.py import spam # from the spam.py import spam money = 111111 spam.read1() # 'spam modular :1000' spam.change() print(spam.money) # 0 print(money) # 111111

Import rename :smt Variable pointing to the span The module's namespace

# run.py import spam as sm money = 111111 sm.money sm.read1() # 'spam modular :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

2、from Module name import Specific function

The grammar is as follows :

from modname import name1[, name2[, ... nameN]]

This declaration does not import the entire module into the current namespace , It will only introduce one or more functions in the module .

from...import... Imported modules , Access does not need to be prefixed .

from...import... The first import of the module happened 3 thing :

Create a module namespace based on the module

File corresponding to the execution module , Throw all the names generated during execution into the module's namespace

Get a name in the namespace of the current execution file , The name points directly to a name in the module , It means you can use it without any prefix

advantage : No prefixes , More streamlined code

shortcoming : It is easy to conflict with the name in the namespace of the current execution file

# run.py from spam import money
from spam import money,read1 money = 10 print(money) # 10

rom … import * sentence : Import all the functions in the file :

# spam.py __all__ = ['money', 'read1'] # Only import 'money' and 'read1'
# run.py from spam import * # Import spam.py All functions within , But it will be limited to __all__ money = 111111 read1() # 'spam modular :1000' change() read1() # 'spam modular :0' print(money) # 111111

3、 Loop in

Circular import occurs in the following cases :

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

You can solve the problem of circular import by using the feature that only syntax is recognized in the function definition stage , Or solve the problem of circular import in essence , But the best solution is to avoid circular import .

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

Option two :

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

4、dir() function

Built in functions dir() You can find all the names defined within the module . Return as a list of strings :

dir(sys) ['__displayhook__', '__doc__', '__excepthook__', '__loader__', '__name__', '__package__', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_debugmallocstats', '_getframe', '_home', '_mercurial', '_xoptions', 'abiflags', 'api_version', 'argv', 'base_exec_prefix', 'base_prefix', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dont_write_bytecode', 'exc_info', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 'getcheckinterval', 'getdefaultencoding', 'getdlopenflags', 'getfilesystemencoding', 'getobjects', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'getswitchinterval', 'gettotalrefcount', 'gettrace', 'hash_info', 'hexversion', 'implementation', 'int_info', 'intern', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit', 'setswitchinterval', 'settrace', 'stderr', 'stdin', 'stdout', 'thread_info', 'version', 'version_info', 'warnoptions']

If there is no given parameter , that dir() The function lists all the names currently defined :

a = [1, 2, 3, 4, 5] import fibo fib = fibo.fib print(dir()) # Get a list of attributes defined in the current module # ['__builtins__', '__name__', 'a', 'fib', 'fibo', 'sys'] b = 5 # Create a new variable 'a' print(dir()) # ['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'a', 'b'] del b # Delete variable name a print(dir()) # ['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'a']

3、 ... and 、 Module search path

1、 The order in which modules are found when importing modules

1、 First from the memory has been imported into the module to find

If we're running run.py When you file , Quickly delete mmm.py file , We will find that the file will continue to run , And never report a mistake , because mmm Has been imported into memory . If we run it again run.py When an error , because mmm.py It has been deleted .

# test.py import m1 # from m1.py Imported from the file , And then it generates m1 The module's namespace import time # Delete m1.py file ,m1 The module's namespace still exists time.sleep(10) import m1 # Don't complain , It must not be from the file m1 modular , It's from memory 

2、 Built in modules

Verify first from the built-in , I won't find a custom one first time.py file .

# time.py print('from time.py') # run.py import time print(time) #

3、 environment variable sys.path In looking for ( emphasize :sys.path The first value of is the folder where the current execution file is located )

import sys for n in sys.path: print(n) # C:\PycharmProjects\untitled\venv\Scripts\python.exe C:/PycharmProjects/untitled/hello.py # C:\PycharmProjects\untitled # C:\PycharmProjects\untitled # C:\Python\Python38\python38.zip # C:\Python\Python38\DLLs # C:\Python\Python38\lib # C:\Python\Python38 # C:\PycharmProjects\untitled\venv # C:\PycharmProjects\untitled\venv\lib\site-packages

If mmm.py stay C:\PycharmProjects\untitled\day16 Under the path , The path of the execution file is C:\PycharmProjects\untitled, If the normal import will report an error , We can C:\PycharmProjects\untitled\day16 Add to environment variables sys.path in , Prevent error reporting .

# run.py import sys sys.path.append(r'C:\PycharmProjects\untitled\day16') print(sys.path) import mmm mmm.f1()

2、 The search path is based on the execution file

Our directory structure is assumed as follows , The code in the file is :

and hello and spam.py Not in the same directory , therefore run.py The environment variable of cannot be found directly m2, Need to import from folder

from aa import spam print(spam.money)

Four 、Python There are two uses for files

When a module is first introduced by another program , Its main program will run . If we want to introduce modules , A block in a module does not execute , We can use name Property to make the block execute only when the module itself is running .

python There are two uses for files , One is the execution file ; The other is imported as a module .

Each module has one name attribute , When the value is 'main' when , Indicates that the module itself is running , Otherwise it's introduced .

1、 When run.py When it's running ,aaa.py As a reference module , its name == 'aaa'( Module name ), Will execute aaa.py Medium f1().

# aaa.py x = 1 def f1(): print('from f1') f1() # run.py import aaa

2、aaa.py When treated as an executable , add name == 'main', Separate operation aaa.py Will execute aaa.py Medium f1(). run.py The runtime prevents execution f1().

# aaa.py x = 1 def f1(): print('from f1') if __name__ == '__main__': f1()

5、 ... and 、 package

Package is a kind of management Python The form of the module namespace , The essence of a bag is to contain .py The file folder for .

Package adoption " Point module name ". For example, the name of a module is A.B, So he means a bag A Sub modules in B .

The directory contains only one called init.py Is a package .

When importing a package ,Python Will be based on sys.path To find the subdirectories contained in this package .

Three things that happen when importing packages :

Create a package's namespace

Because the package is a folder , Unable to execute package , So execute the .py file , Store the names generated during execution in the package namespace ( That is, the names stored in the package name space are all from .py)

Get a name in the current executable file aaa,aaa Is pointing to the package's namespace

The import package is under the import package .py, Import m1 It's import m1 Medium init.

1、 Two ways to import :

import ... :

import item.subitem.subsubitem This form of import , Except for the last term , All have to be bags , The last item can be a module or a package , No, but class , The name of a function or variable .

from ... import...:

When using from package import item In this form , Corresponding item It can be a sub module in the package ( subpackage ), Or any other name in the package , Like functions , Class or variable .

2、import Import modules in package

import You can import only specific modules in one package at a time , He must use his full name to access .

import aaa.bbb.m3 print(aaa.bbb.m3.func3())

import Method cannot import function 、 Variable :import aaa.bbb.m3.f3 error

3、from import The way :

Import specific modules in the module

This method does not need those lengthy prefixes to access

from aaa.bbb import m3 print(m3.func3())

Import specific functions in the module

This method does not need those lengthy prefixes to access

from aaa.bbb.m3 import func3 print(func3())

4、 Absolute import and relative Import

Absolutely import :

# aaa/.py from aaa.m1 import func1 from aaa.m2 import func2

Relative Import :

. Represents the folder where the currently imported file is located

.. Represents the upper level of the folder where the currently imported file is located

... Represents the upper level of the folder where the currently imported file is located

from .m1 import func1 from .m2 import func2

5、from...import *

The import statement follows the following rules : If the package definition file init.py There is one called all List variables of , So in use from package import * All the names in this list will be imported as package contents .

Here's an example , stay :file:sounds/effects/init.py Contains the following code :

__all__ = ["echo", "surround", "reverse"]

This means that when you use from sound.effects import * In this way , You can only import the three sub modules in the package .

6、 ... and 、 Directory specification for software development

In order to improve the readability and maintainability of the program , We should design a good directory structure for software , This is as important as the standard coding style , In short, the software code is divided into file directory . Suppose you want to write a ATM Software , You can manage your software code according to the following directory structure :

ATM/ |-- core/ | |-- src.py # Business core logic code | |-- api/ | |-- api.py # Interface file | |-- db/ | |-- db_handle.py # Operation data file | |-- db.txt # Store data files | |-- lib/ | |-- common.py # sharing | |-- conf/ | |-- settings.py # Configuration related | |-- bin/ | |-- run.py # The startup file of the program , It is usually placed in the root directory of the project , Because at runtime, the folder where the running file is located will be taken as sys.path The first path , This eliminates the need to deal with environment variables | |-- log/ | |-- log.log # Log files | |-- requirements.txt # Store the external information that the software depends on Python Package list , See https://pip.readthedocs.io/en/1.1/requirements.html |-- README # Project description document 

settings.py

# settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DB_PATH = os.path.join(BASE_DIR, 'db', 'db.txt') LOG_PATH = os.path.join(BASE_DIR, 'log', 'user.log') # print(DB_PATH) # print(LOG_PATH)

common.py

# common.py import time from conf import settings def logger(msg): current_time = time.strftime('%Y-%m-%d %X') with open(settings.LOG_PATH, mode='a', encoding='utf-8') as f: f.write('%s %s' % (current_time, msg))

src.py

# src.py from conf import settings from lib import common def login(): print(' land ') def register(): print(' register ') name = input('username>>: ') pwd = input('password>>: ') with open(settings.DB_PATH, mode='a', encoding='utf-8') as f: f.write('%s:%s\n' % (name, pwd)) # Log ...... common.logger('%s Registered successfully ' % name) print(' Registered successfully ') def shopping(): print(' shopping ') def pay(): print(' payment ') def transfer(): print(' Transfer accounts ') func_dic = { '1': login, '2': register, '3': shopping, '4': pay, '5': transfer, } def run(): while True: print(""" 1 land 2 register 3 shopping 4 payment 5 Transfer accounts 6 sign out """) choice = input('>>>: ').strip() if choice == '6': break if choice not in func_dic: print(' Enter wrong command , silly ass ') continue func_dic[choice]()

run.py

# run.py import sys import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(BASE_DIR) from core import src if __name__ == '__main__': src.run()

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved