Python模組以及日曆常見用法

bug--maker發表於2018-09-18
  • 模組
  • 對於專案來說,程式檔案不會出現在一個檔案裡面,所以需要將很多功能相似的函式進行分組,分別放到不同的檔案中,而且對於每一個檔案的大致功能使用檔名稱來進行區別,通常來說每一個*.py檔案就是一個模組;
    1. 模組用於提高程式碼的可維護性
    1. 可以提高程式碼的可複用度;
    1. 可以引用其他的模組,包括內建模組[Python提供的]以及第三方模組以及自定義模組;
    1. 可以避免函式名和變數名的衝突
  • sys模組
  • sys:主要是使用者獲取命令列引數的列表
import sys

print(sys.argv)

for i in sys.argv:
    print(i)
name = sys.argv[1]
age = sys.argv[2]
hoby = sys.argv[3]

print(name, age, hoby)
  • 輸出的結果
    這裡寫圖片描述

  • 自動查詢所需模組所需路徑的列表

import sys

print(sys.argv)

for i in sys.argv:
    print(i)
name = sys.argv[1]
age = sys.argv[2]
hoby = sys.argv[3]

print(name, age, hoby)

print(sys.path)
  • 檢視結果
    這裡寫圖片描述
  • 模組引入的方式
  • 系統模組
import module name [1,module name2, module name1]
  • 自定義模組,一個模組只會被引入一次,防止模組被多次引入;
import module name    //模組名和檔名在同一個目錄,否則就需要放在指定的目錄裡面;
  • 使用自定義模組的格式
//匯入的一種方式
import hello
hello.sayhello()       //模組名.方法[函式/變數]

//另一種引入的方式 引入模組的一種方法 從模組中匯入某個指定的方法
from hello import tomorrow[,name1, name2]

tomorrow()            //這裡不需要加函式名
  • 對於from ... import ... 這種匯入方式是存在弊端的,如果在當前定義和模組裡面的同名函式,就會導致模組裡面的函式被覆蓋
from hello import tomorrow

def tomorrow():
    print("tomorrow is a good day")

tomorrow()
  • 對於第一種方式就不存在上面的問題
import hello

def tomorrow():
    print("tomorrow is a good day")

hello.tomorrow()
tomorrow()

//最後一種匯入方式  用於將一個模組中所有的方法變數都進行匯入
from hello import *
  • 和第二種一樣存在同樣的弊端,不建議使用這種方式

  • 關於__name__屬性:模組表示的是一個可執行的*.py,如果不希望模組在被引入的過程中被執行,可以用__name__屬性,來使程式僅僅呼叫模組中的一部分;

  • 每一個模組都存在一個__name__屬性,當其值為__main__,表示執行模組本身

def man():
	pass

if __name__ == "__main__":
    man()
else:
    def sayhello():
        print("hello python")

    def today():
        print("today is new day")

    def tomorrow():
        print("hello")
  • 如果模組當做可執行檔案執行的時候,__name__的值,就是__main__,如果當做模組不希望執行的時候,__name__的值是不確定的

  • 輸出指定年月的日曆

import calendar
print(calendar.month(2018, 6))

     June 2018
Mo Tu We Th Fr Sa Su
             1  2  3
 4  5  6  7  8  9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30
  • 返回某一個年的日曆
print(calendar.calendar(2018))

                                  2018

      January                   February                   March
Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
 1  2  3  4  5  6  7                1  2  3  4                1  2  3  4
 8  9 10 11 12 13 14       5  6  7  8  9 10 11       5  6  7  8  9 10 11
15 16 17 18 19 20 21      12 13 14 15 16 17 18      12 13 14 15 16 17 18
22 23 24 25 26 27 28      19 20 21 22 23 24 25      19 20 21 22 23 24 25
29 30 31                  26 27 28                  26 27 28 29 30 31

       April                      May                       June
Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
                   1          1  2  3  4  5  6                   1  2  3
 2  3  4  5  6  7  8       7  8  9 10 11 12 13       4  5  6  7  8  9 10
 9 10 11 12 13 14 15      14 15 16 17 18 19 20      11 12 13 14 15 16 17
16 17 18 19 20 21 22      21 22 23 24 25 26 27      18 19 20 21 22 23 24
23 24 25 26 27 28 29      28 29 30 31               25 26 27 28 29 30
30

        July                     August                  September
Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
                   1             1  2  3  4  5                      1  2
 2  3  4  5  6  7  8       6  7  8  9 10 11 12       3  4  5  6  7  8  9
 9 10 11 12 13 14 15      13 14 15 16 17 18 19      10 11 12 13 14 15 16
16 17 18 19 20 21 22      20 21 22 23 24 25 26      17 18 19 20 21 22 23
23 24 25 26 27 28 29      27 28 29 30 31            24 25 26 27 28 29 30
30 31

      October                   November                  December
Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
 1  2  3  4  5  6  7                1  2  3  4                      1  2
 8  9 10 11 12 13 14       5  6  7  8  9 10 11       3  4  5  6  7  8  9
15 16 17 18 19 20 21      12 13 14 15 16 17 18      10 11 12 13 14 15 16
22 23 24 25 26 27 28      19 20 21 22 23 24 25      17 18 19 20 21 22 23
29 30 31                  26 27 28 29 30            24 25 26 27 28 29 30
                                                    31
  • 判斷閏年
print(calendar.isleap(2000))
True
  • 用於返回某個月的weekday的第一天以及這個月的天數
print(calendar.month(2018, 6))
print(calendar.monthrange(2018,6))

     June 2018
Mo Tu We Th Fr Sa Su
             1  2  3
 4  5  6  7  8  9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30

(4, 30)
  • 返回某個月,以每一週為元素的列表
print(calendar.month(2018, 6))
print(calendar.monthcalendar(2018,6))

     June 2018
Mo Tu We Th Fr Sa Su
             1  2  3
 4  5  6  7  8  9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30

[[0, 0, 0, 0, 1, 2, 3], [4, 5, 6, 7, 8, 9, 10], [11, 12, 13, 14, 15, 16, 17], [18, 19, 20, 21, 22, 23, 24], [25, 26, 27, 28, 29, 30, 0]]
  • 遞迴遍歷目錄處理郵箱格式的檔案
  • 程式碼如下
import os
import collections

def formatFile(path):
    recvPath = "/root/temp/mailfile"
    with open(path,"r") as file:
        while True:
            lineinfo = file.readline()
            #print(lineinfo)
            if len(lineinfo) < 5:
               break
            mailStr = lineinfo.split("----")[0]
            print(mailStr)
            fileType = mailStr.split("@")[1].split(".")[0]
            dirStr = os.path.join(recvPath, fileType)
            if not os.path.exists(dirStr):
                os.mkdir(dirStr)
            filePath = os.path.join(dirStr,fileType + ".txt")
            with open(filePath, "a") as filew:
                filew.write(mailStr + "\n")

def mailprocess(path):
    stack = []
    stack.append(path)
    while len(stack) != 0:
        dirPath = stack.pop()
        fileList = os.listdir(dirPath)

        for fileName in fileList:
            filePath = os.path.join(dirPath, fileName)
            if os.path.isdir(filePath):
                stack.append(filePath)
            else:
                formatFile(filePath)


path = "/root/temp/mail"

mailprocess(path)
  • 第三方模組的安裝
  • 首先確定pip是否安裝

pip -v
  • 然後通過命令安裝
    這裡寫圖片描述
from PIL import Image

picturepath = "/root/PycharmProjects/test/123.jpg"

im = Image.open(picturepath)
print(im.format, im.size, im.mode)

im.thumbnail((640, 400))
im.save("new.jpg", "JPEG")
  • 程式導向

  • 自上而下執行,逐步求精

  • 程式結構通常是若干個模組,各個模組之間的關係儘量簡單,功能上相對獨立;

  • 每一個模組內部都是由順序,選擇和迴圈三種基本結構;

  • 模組的具體使用方法是使用子程式;

  • 程式流程在寫程式時,就已經決定;

  • 物件導向

  • 將資料和對於資料操作的方法放在一起,作為一個相互依賴的整體,成為物件

  • 將同類物件抽取出共性,形成類;

  • 對於類中的大多數資料,只能夠使用本類的方法進行處理;

  • 類通過一個簡單的外部介面與外界發生關係,物件和物件通過訊息進行通訊;

  • 程式的流程在使用者的使用過程中決定;

  • 程式導向和麵向物件

  • 程式導向強調的是功能行為以及解決問題需要的步驟;

  • 物件導向:將功能封裝成物件,強調了具備了那些功能的物件,關注與解決問題需要那些物件;

  • 物件導向是基於程式導向的;

  • 物件導向的特點:

    • 可以將複雜的問題簡單化;
    • 符合思考的習慣
    • 可以根據實際的需求來採用各種物件,如果物件不存在,就建立所需要的物件;
  • 類和物件的關係:

    • 物件表示物件實際存在的個體;
    • 類是對於事物特性的一種抽象;
  • 類的定義

  • 定義類其實就是在定義類中成員的成員變數和成員方法;

  • 類的設計:類名,屬性,行為;

  • object:表示基類,超類,表示的是所有類的父類,一般沒有合適的父類就使用object;

class Person(object): #表示基類,超類,表示的是所有類的父類,一般沒有合適的父類就使用`object`;
	# 定義屬性,本質上就是定義變數
    name = ""
    age = 0
    height = 0
    weight = 0         //這裡定義的就是預設的值,如果建立物件不賦值,使用這裡
	
	# 定義方法(定義函式):方法的引數必須是以self當做第一個引數,self表示的含義就是類的例項 
    def run(self):
        print("run")
    def eat(self, food):
        print("eat" + food)
  • 使用類來例項化物件
格式 物件名 = 類名(引數列表)  沒有引數時,()不能夠省略
xixi = Person()

print(xixi)

<__main__.Person object at 0x7fdaf1613780> //返回值得到的是一個記憶體地址
  • 使用同一個類例項化的物件是不同的物件地址也是不一樣的
xixi = Person()

print(xixi)
print(type(xixi))
print(id(xixi))

js = Person()

print(js)
print(type(js))
print(id(js))
  • 物件一般是儲存在堆區,變數一般是在棧區的;
    這裡寫圖片描述

  • 訪問物件的屬性和方法

格式: 物件名.屬性名
賦值: 物件名.屬性名 = 

xixi.name = "hello"
xixi.age = 16
xixi.height = 180

print(xixi.name, xixi.age, xixi.height)
  • 對於物件來說,如果不進行賦值,就不會使用預設的值;
  • 訪問方法:
格式:物件名.方法名(引數列表)
xixi.eat("apple")
  • 使用上面的方法建立的物件都是一樣的,這裡希望每個物件建立出來都是不一樣的,需要藉助於建構函式來完成
  • 建構函式__init__():在使用類建立物件的時候,自動呼叫,如果不顯示的寫出建構函式,預設也是存在一個預設的空的建構函式;
xixi.name = "hello"
xixi.age = 16
xixi.height = 180

print(xixi.name, xixi.age, xixi.height)

xixi.eat("apple")
  • 建立物件時的執行結果
    這裡寫圖片描述
  • 所以這裡可以藉助於建構函式來傳遞引數,完成每個物件的初始化
class Person(object):
    def run(self):
        print("run")
    def eat(self, food):
        print("eat " + food)
    def __init__(self, name, age, height, weight):  //屬性定義
        self.name = name
        self.age = age
        self.height = height
        self.weight = weight
        print("__init__")

xixi = Person("hello", 19, 180, 66)
print(xixi.name, xixi.age, xixi.height, xixi.weight)

hello
19
180
66
__init__
  • self的含義:
    • self代表的是類的例項,而不是類;
    • 哪個物件呼叫方法,該方法中的self就代表哪個物件;
    • self.__class__:代表的是類名;
class Person(object):
    name = ""
    age = 0
    height = 0
    weight = 0

    def run(self):
        print("run")
    def eat(self, food):
        print("eat " + food)
    def say(self):
        print("my name is %s,and i am %d years old" %(self.name, self.age))
        print(self.__class__)
    def __init__(self, name, age, height, weight):
        self.name = name
        self.age = age
        self.height = height
        self.weight = weight
        print("__init__")


xixi = Person("hello", 19, 180, 66)
#print(xixi.name, xixi.age, xixi.height, xixi.weight)
xixi.say()

js = Person("js", 20, 150, 60)
js.say()

__init__
my name is hello,and i am 19 years old
<class '__main__.Person'>
__init__
my name is js,and i am 20 years old
<class '__main__.Person'>
  • self不是關鍵字,可以換,但是不建議換;
  • 解構函式
  • 在物件釋放時,自動呼叫;
  • 釋放物件:
    • 程式結束時,物件自動釋放;
    • 使用del刪除變數時,程式自動釋放;
    • 對於自定義的函式,在函式呼叫完成之後,就會自動釋放;
  • 物件釋放之後,無法再次使用;
解構函式: __del__() 
lass Person(object):
    def run(self):
        print("run")
    def eat(self, food):
        print("eat " + food)
    def say(self):
        print("my name is %s,and i am %d years old" %(self.name, self.age))
        print(self.__class__)
    def __init__(self, name, age, height, weight):
        self.name = name
        self.age = age
        self.height = height
        self.weight = weight
        print("__init__")
    def __del__(self):
        print("xigou funcation")

xixi = Person("hello", 19, 180, 66)
#print(xixi.name, xixi.age, xixi.height, xixi.weight)
xixi.say()


del xixi

js = Person("js", 20, 150, 60)
js.say()

del js
  • 重寫函式
  • 將函式重新定義,並且重寫一遍,
  • 重寫函式包括__str__();
    • 使用重寫函式可以輸出物件裡面所有的屬性值,方便在進行輸出控制;
    • 在呼叫print列印物件時,會自動呼叫,是一個描述物件的方法;
  • 以及以及__repr__():
    • 這個是給機器使用的,在Python直譯器中直接使用物件名稱時,呼叫的方法,在函式呼叫時,如果不存在__str__(),也會使用__repr__()
 def __str__(self):
        return "%s %d %d %d" % (self.name, self.age, self.height, self.weight)
     
hello 19 180 66
xigou funcation   
  • 訪問限制
  • 限制物件訪問類裡面的某些屬性,這些屬性可能是類裡面使用的,需要在屬性前__屬性名,在Python中,如果在屬性前加兩個__,屬性就變為private;
  • 類似於__name__的變數屬於特殊變數,但是不是私有變數,外部是可以直接訪問的;
  • 類似於_name_這樣的外部變數也是可以進行訪問的,按照約定的規則,是不能夠訪問這種型別的變數的;
 def __init__(self, name, age, height, weight, money):
        self.name = name
        self.age = age
        self.height = height
        self.weight = weight
        self.__money = money
        print("__init__")
  
 print(xixi.__money)
Traceback (most recent call last):
  File "/root/PycharmProjects/test/person.py", line 27, in <module>
    print(xixi.__money)
AttributeError: 'Person' object has no attribute '__money'
  • 如果訪問私有屬性,就會出錯;對於下面這種情況,是因為動態語言的特性,支援動態新增屬性;
xixi.__money = 10
print(xixi.__money)
  • 內部是可以使用這個變數的
    def run(self):
        print("run")
        print(self.__money)
    def __init__(self, name, age, height, weight, money):
        self.name = name
        self.age = age
        self.height = height
        self.weight = weight
        self.__money = money
        print("__init__")

xixi.run()
  • 類可以通過定義方法向物件提高修改私有變數的方法
    def setMoney(self, money):
        if money < 0 :
            money = 0
        self.__money = money
    def getMoney(self):
        return self.__money
  • 不能夠直接訪問xix._money是因為Python__money改為了_Person__money,可以通過後面這個變數來進行訪問
xixi._Person__money = 30  //並且也直接修改了私有變數的值

xixi.run()
  • 但是是不建議這樣進行使用的,對於不同版本的直譯器,解釋出來的結果是不一樣的;
  • 小程式
class bulletBox(object):
    def __init__(self, count):
        self.bulletCount = count

class gun(object):
    def __init__(self, bulletBox):
        self.bulletBox = bulletBox
    def shoot(self):
        if self.bulletBox.bulletCount == 0:
            print("no bellit")
        else:
            self.bulletBox.bulletCount -= 1
            print("left is %d" %(self.bulletBox.bulletCount))

class person(object):
    def __init__(self, gun):
        self.gun = gun
    def fire(self):
        self.gun.shoot()
    def loadBullet(self, count):
        self.gun.bulletBox.bulletCount += count


bulletBox = bulletBox(5)
gun = gun(bulletBox)

per = person(gun)

per.fire()
per.fire()
per.fire()
per.loadBullet(3)
per.fire()

相關文章