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

[python core] module related knowledge

編輯:Python

文章目錄

  • 模塊Module
    • 定義
    • 作用
    • Invoke the file preparation in the same directory
    • 使用方法
    • 練習1
    • 練習2
  • 模塊變量
  • 加載過程
  • 分類
  • 內置模塊time
    • 練習1
    • 練習2
  • 總結

模塊Module

定義

包含一系列數據、函數、類的文件,通常以.py結尾.

作用

多人合作開發

Invoke the file preparation in the same directory

使用方法

"""
模塊
"""
# 導入方式1:
#本質∶使用變量名module01Associated module address
# import module01
# module01.fun01()
# my02 = module01.MyClass02()
# my02.fun02()
#模塊1
# 模塊1的fun01
# MyClass02--fun02
#asGive the imported member another name
import module01 as m01
m01.fun01()
my02 = m01.MyClass02()
my02.fun02()
# 導入方式2:
# 本質︰Imports the specified member into the current module scope
#小心:The imported member should not have the same name as the current module member
# from module01 import fun01
# from module01 import MyClass02
# fun01()# 模塊1的fun01
# # if present in the current modulefun01的函數:
# def fun01():
# print("當前模塊fun01")
# fun01()#當前模塊fun01
# my02 = MyClass02()
# my02.fun02()
# 模塊1
# 模塊1的fun01
# 當前模塊fun01
# MyClass02--fun02
# 導入方式3:
# 本質︰Imports all members of the specified module into the current module scope
#小心:The imported member conflicts with other module members
# from module01 import *
# fun01()
# my02 = MyClass02()
# my02.fun02()
# 模塊1
# 模塊1的fun01
# MyClass02--fun02

module01.py

print("模塊1")
def fun01():
print("模塊1的fun01")
class MyClass02:
def fun02(self):
print("MyClass02--fun02")

練習1

將之前的Vector2和DoublelistHelper定義到
double_list_helper.py模塊中.
在exercise01.py模塊中,實現
(1)in a two-dimensional list,獲取13位置,向左,3個元素.
(2)in a two-dimensional list﹐獲取22位置,向上,2個元素.
(3)in a two-dimensional list﹐獲取03位置,向下,2個元素.
要求∶Use three import methods.
體會∶which one is more suitable.

import double_list_helper
#print(double_list_helper.DoublelistHelper.elements(double_list_helper.list01, double_list_helper.Vector2(1, 3), double_list_helper.Vector2.left(), 3))#['12', '11', '10']
# print(double_list_helper.DoublelistHelper.elements(double_list_helper.list01, double_list_helper.Vector2(2, 2), double_list_helper.Vector2.up(), 2))#['12', '02']
print(double_list_helper.DoublelistHelper.elements(double_list_helper.list01, double_list_helper.Vector2(0, 3), double_list_helper.Vector2.down(), 2))#['13', '23']
from double_list_helper import Vector2
from double_list_helper import DoublelistHelper
from double_list_helper import list01
# print(DoublelistHelper.elements(list01, Vector2(1, 3), Vector2.left(), 3))#['12', '11', '10']
#print(DoublelistHelper.elements(list01, Vector2(2, 2), Vector2.up(), 2))#['12', '02']
print(DoublelistHelper.elements(list01, Vector2(0, 3), Vector2.down(), 2))#['13', '23']
from double_list_helper import *
# print(DoublelistHelper.elements(list01, Vector2(1, 3), Vector2.left(), 3))#['12', '11', '10']
#print(DoublelistHelper.elements(list01, Vector2(2, 2), Vector2.up(), 2))#['12', '02']
print(DoublelistHelper.elements(list01, Vector2(0, 3), Vector2.down(), 2))#['13', '23']

double_list_helper.py

class Vector2:
def __init__(self,x,y):
self.x = x
self.y = y
@staticmethod
def left():
return Vector2(0, -1)
@staticmethod
def up():
return Vector2(-1, 0)
@staticmethod
def down():
return Vector2(1, 0)
list01 = [
["00", "01", "02", "03"],
["10", "11", "12", "13"],
["20", "21", "22", "23"],
]
list_result = []
class DoublelistHelper:
@staticmethod
def elements(target,vect_pos,vect_dir,count):
for item in range(count):
vect_pos.x += vect_dir.x
vect_pos.y += vect_dir.y
list_result.append(target[vect_pos.x][vect_pos.y])
return list_result

練習2

The student management system is divided into four modules:
M–> model.py 數據模塊
V–> ui.py`界面模塊
C–> bll.py 業務邏輯模塊
將調用View的代碼–> main.py 入口模塊
model.py

"""
定義數據模型
"""
class StudentModel:
"""
學生模型
"""
def __init__(self,name="",age=0,score=0.0,id=0):
"""
創建學生對象
:param name::姓名,str類型
:param age:年齡,int類型
:param score:成績,float類型
:param id: 編號(Unique identifier for this student object)
"""
self.name = name
self.age =age
self.score = score
self.id = id

ui.py

"""
界面代碼
"""
from model import *
from bll import *
class StudentManagerView:
"""
學生管理器視圖
"""
def __init__(self):
self.__manager = StudentManagerController()
def __display_menu(self):
print("1)添加學生")
print("2)顯示學生")
print("3)刪除學生")
print("4)修改學生")
print("5)按照成績升序顯示學生")
def __select_menu(self):
item = input("請輸入∶")
if item == "1":
self.__input_student()
elif item == "2":
self.__output_students(self.__manager.stu_list)
elif item == "3":
self.__delete_student()
elif item == "4":
self.__modify_student()
elif item == "5":
self.__output_student_by_score()
def main(self):
"""
界面視圖入口
"""
while True:
self.__display_menu()
self.__select_menu()
def __input_student(self):
name = input("請輸入姓名∶")
age = int(input("請輸入年齡:"))
score = float(input("Please enter your grades∶"))
stu = StudentModel(name, age, score)
self.__manager.add_student(stu)
def __output_students(self,list_output):
for item in list_output:
print(item.id,item.name,item.age,item.score)
def __delete_student(self):
id = int(input("請輸入編號∶"))
if self.__manager.remove_student(id):
print("刪除成功")
else:
print ("刪除失敗")
def __modify_student(self):
stu = StudentModel()
stu.id = int(input("請輸入需要修改的學生編號:"))
stu.name = input("Please enter the new student name:")
stu.age = int(input("請輸入新的學生年齡:"))
stu.score = float(input("請輸入新的學生成績∶"))
if self.__manager.update_student(stu):
print("修改成功")
else:
print("修改失敗")
def __output_student_by_score(self):
self.__manager.order_by_score()
self.__output_students(self.__manager.stu_list)

bll.py

"""
業務邏輯處理
"""
class StudentManagerController:
"""
學生管理控制器,負責業務邏輯處理.
"""
# 類變量,表示初始編號.
init_id = 1000
def __init__(self):
self.__stu_list = []
@property
def stu_list(self):
"""
學生列表
:return: 存儲學生對象的列表
"""
return self.__stu_list
def add_student(self,stu_info):
"""
添加一個新學生
:param stu_info:沒有編號的學生信息
"""
stu_info.id = self.__generate_id()
#self.stu_list.append(stu_info)
self.__stu_list.append(stu_info)
def __generate_id(self):
StudentManagerController.init_id += 1
return StudentManagerController.init_id
def remove_student(self,id):
"""
Remove student information by number
:param id:編號
:return:是否移除
"""
for item in self.__stu_list:
if item.id == id:
self.__stu_list.remove(item)
return True#表示移除成功
return False#表示移除失敗
def update_student(self,stu_info):
"""
根據stu_info.id修改其他信息
:param stu_info: 學生對象
:return: 是否修改成功
"""
for item in self.__stu_list:
if item.id == stu_info.id:
item.name = stu_info.name
item.age = stu_info.age
item.score = stu_info.score
return True#表示修改成功
return False#表示修改失敗
def order_by_score(self):
"""
根據成績,對self.__stu_list進行升序排列
"""
for r in range(len(self.__stu_list)-1):
for c in range(r+1,len(self.__stu_list)):
if self.__stu_list[r].score > self.__stu_list[c].score:
self.__stu_list[r],self.__stu_list[c] = self.__stu_list[c],self.__stu_list[r]

main.py

"""
程序入口
"""
from ui import *
view = StudentManagerView()
view.main()

注意:from 模塊 import *
模塊中以下劃線(_)開頭的屬性,不會被導入,通常稱這些成員為隱藏成員.

模塊變量

  1. __all__變量:定義可導出成員,僅對from xx import * 語句有效.
    exercise01.py

    from module01 import *
    MyClass.fun03()
    _fun02()

module01.py

#定義:Which members of the current module can be usedfrom 模塊 import * 導入
__all__ = ["fun01","MyClass","_fun02"]
print("模塊1")
def fun01():
print("模塊1的fun01")
#Just a member used inside a module,可以以單下劃線開頭.
#只限於from 模塊 import * 有效
def _fun02():
print("模塊1的fun02")
class MyClass:
@staticmethod
def fun03():
print("MyClass -- fun03")
  1. _doc__變量:文檔字符串.

    #可以通過該屬性﹐查看文檔注釋
    print(doc)

  2. __file__變量:模塊對應的文件路徑名.

    #Returns the absolute path of the current module(Calculated from the system root directory)
    print(file)

  3. __name__變量:模塊自身名字,可以判斷是否為主模塊.
    當此模塊作為主模塊(第一個運行的模塊)運行時,__name__綁定’main”,不是主模塊,而是被其它模塊導入時,存儲模塊名.

    #現象
    #The main module is called ∶__main__
    #Non-main modules are called ∶真名
    print(name)
    #作用1∶測試代碼,Only run from the current module will execute.Not the main module does not execute.
    #Imported and used by other modules
    #以下為測試代碼,Only run from the current module will execute.
    if name == “main_”:

    #作用2:Restrictions are only enforced from the current module.Only the main module is executed.
    在main.py裡面加if name == “main_”:

加載過程

在模塊導入時,模塊的所有語句會執行.
,如果一個模塊已經導入,則再次導入時不會重新執行模塊內的語句.

分類

  1. 內置模塊(builtins),在解析器的內部可以直接使用.
  2. 標准庫模塊,安裝Python時已安裝且可直接使用.(randomClasses are the standard library)
  3. 第三方模塊(通常為開源),需要自己安裝.
  4. 用戶自己編寫的模塊(可以作為其他人的第三方模塊).

內置模塊time

"""
時間處理
"""
import time
#1.獲取當前時間戳(從1970年1月1The number of seconds elapsed since day)
#1652072713.4642925
print(time.time())
#時間元組(年,月,日,時,分﹐秒,一周的第幾天,一年的第幾天,夏令時)
#時間戳 ---》時間元組
print(time.localtime(1652072713))
#The time is obtained through the operation of the tuple
tuple_time = time.localtime()
for item in tuple_time:
print(item)
print(tuple_time[1])#獲取月
#The time is obtained through the operation of the class
print(type(tuple_time))
# print(time.struct_time)
print(tuple_time.tm_year)#獲取年
#時間元組 --->時間戳
print(time.mktime(tuple_time))
#時間元組 -->元組
str_timo01 = time.strftime("%Y / %m / %d %H : %M : %S " ,tuple_time)
print(str_timo01)#2022 / 05 / 09 13 : 23 : 02
#str --> 時間元組
tuple_time02 = time.strptime(str_timo01,"%Y / %m / %d %H : %M : %S ")
print(tuple_time02)

練習1

定義函數,根據年月日,返回星期數.
"星期一“
"星期二”
"星期三”
思路∶
年月日–>時間元組
Time tuple–>星期
星期–>格式

import time
def get_wday(year,month,day):
"""
獲取星期數
:param year:年
:param month:月
:param day:天
:return:星期幾
"""
tuple_time = time.strptime("%d - %d - %d"%(year,month,day), "%Y - %m - %d")
dict_weeks = {
0:"星期一",
1:"星期二",
2:"星期三",
3:"星期四",
4:"星期五",
5: "星期六",
6: "星期日",
}
return dict_weeks[tuple_time[6]]
re = get_wday(2022,5,9)
print(re)#星期一

練習2

練習2∶According to birthday(年月日),計算活了多少天.
思路∶
年月日–>出生時間
當前時間–>出生時間
計算天數

import time
def life_days(year,month,day):
"""
Calculate how many days you live based on your birthday
:param year: 年
:param month: 月
:param day: 日
:return: days to live
"""
tuple_time = time.strptime("%d - %d - %d"%(year,month,day), "%Y - %m - %d")
life_time = time.time()-time.mktime(tuple_time)
return int(life_time / 60 / 60 // 24)
print(life_days(1991,10,12))#11167

總結

模塊導入:

import 模塊
模塊.成員名
--------------------
import 模塊 as 別名
別名.成員名
-------------------
from 模塊 import 成員
直接使用成員
-------------------
from 模塊 import *

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