python module calls Problem Description

First, call the built-in module

1. Call module

import time
print(time.ctime())

2. Direct introduction the ctime () function

from time import ctime
print(ctime())

3. introduced at a plurality of time functions module

from time import *

4. All import function module at time

This method is suitable for the module will be applicable to all the functions, but do not want to add time before each function

from time import *
print(ctime())
sleep(2)
print(ctime())

If the function is just the same as an import function own definition, you can use "as" to rename

from time import sleep as sys_sleep

def sleep():
    print("this is I defined sleep")

sleep()
sys_sleep(2)

Second, custom module

Here Insert Picture Description

  1. calculator.py
def add(a, b):
    return a + b
  1. test.py
from calculator import add

print(add(4, 5))

NOTE: When the test.py After running, one more __pycache / calculator.cpython-37.pyc project file directory module in order to improve the speed of loading, each module will be placed in the module precompiled folder __pycache__ module, named module.version.pyc

Third, the Cross-calling module

Here Insert Picture Description

This case, the first use "sys.path" View the search path python found module is not in the search path, which will lead to, we could not import files directly calculator

Solution: We just need to be added to the next folder module search path to the python

1. Add the absolute path (poor portability)

import sys
sys.path.append("D:\\python\\demo\\project2\\module")
from calculator import add
print(add(2, 3))

2. Add the relative path (relative must ensure that the directory hierarchy does not change)

import sys
import os

project_path = os.path.dirname(os.path.dirname(abspath(__file__)))
sys.path.append(project_path + 'module')

from calculator import add
print(add(2, 3))

Fourth, write self-test codes

calculator.py

def add(a, b):
    return a + b

if __name__ == '__main__':
# 测试代码
    c = add(3, 5)
    print(c)
Published 20 original articles · won praise 30 · views 30000 +

Guess you like

Origin blog.csdn.net/ever_siyan/article/details/104538740