Python basic grammar knowledge (4) - packages and modules

module

Example 1: Import a specific function in a module

# 只导入time模块中的sleep方法,可以直接使用sleep调用不用加time.
from time import sleep
print("hello")
sleep(500)
print("fine")

# 只导入time模块中的sleep方法,并给sleep起别名为sl
from time import sleep as sl
print("hello")
sl(500) # !!!
print("fine")

Example 2: Custom Module

When a custom module writes test code and imports the module in other code files, the test code will also be called, namely:

Note that the following are the codes of the two files

# my_moudle.py
def add(x, y):
    print(f"{
      
      x} + {
      
      y} = {
      
      x+y}")

add(8, 9)

# aa.py
import my_moudle
my_moudle.add(22, 12)

Execute aa.py output:
8 + 9 = 17
22 + 12 = 34

If you don't want to execute add(8, 9) in my_moudle.py, you can modify the code:

# my_moudle.py
def add(x, y):
    print(f"{
      
      x} + {
      
      y} = {
      
      x+y}")

if __name__ == '__main__':
    add(8, 9)

__name__It is a built-in variable of each py file, only the running py file will be__main__

Example 3: __all__ global variable

# my_moudle.py
__all__ = ['add'] # 其他文件  以from my_moudle import * 导入,则只能用add函数
def add(x, y):
    print(f"{
      
      x} + {
      
      y} = {
      
      x+y}")

def sub(x, y):
    print(f"{
      
      x} - {
      
      y} = {
      
      x-y}")

python package

The python package is a folder , which contains modules, namely python files , and an additional one__init__.py

Create a python package method

insert image description here

insert image description here

Suppose there are two module files my_moudle1.py and my_moudle2.py under the folder

# my_moudle1.py
def print1():
    print("模块1功能")

# my_moudle2.py
def print2():
    print("模块2功能")

used in aa.py

# 这样导入,调用函数要写包名.模块名.方法名
import my_package.my_moudle1
import my_package.my_moudle2

my_package.my_moudle1.print1()
my_package.my_moudle2.print2()

# 这样导入,调用函数要写模块名.方法名
from my_package import my_moudle1
from my_package import my_moudle2

my_moudle1.print1()
my_moudle2.print2()

# 这样导入,调用函数只要写方法名
from my_package.my_moudle1 import print1
from my_package.my_moudle2 import print2

print1()
print2()

list sort method

That is, use your own defined comparison function to sort

my_list=[["a", 33], ["b", 55], ["c", 11]]

# 基于有名函数排序
# 表明按照element 的第二个元素进行排序
def choose_sort_key(element):
    return element[1]

# reverse=True 表明是降序排列
#my_list.sort(key = choose_sort_key, reverse=True)

# 基于lambda匿名函数来降序排序
my_list.sort(key=lambda element:element[1], reverse=True)

print(my_list)

Output result:
[['b', 55], ['a', 33], ['c', 11]]

Guess you like

Origin blog.csdn.net/qq_42120843/article/details/131159073