1、python基礎速成


基礎模塊

def prt(age,name):#函數定義

   print("%s is %d 年齡 old"%(name,age))

 

if __name__=="__main__":#程序入口

   print("Hello World")

   prt(45,"gaici")    

 

獲取輸入:使用input()函數

name=input("you name ?")   

 

python的文件類型主要分為3類,分別是源代碼、字節代碼和優化代碼。

1、源代碼:文件以“py”為擴展名,“pyw”是圖形用戶接口的源文件的擴展名。

2、字節代碼:python源文件經過編譯后生成擴展名為"pyc"的文件,此文件是與平台無關的,可通過腳本生成該類型的文件。

import py_compile

py_compile.compile("ps.py")

運行后即可得到ps.pyc文件

3、優化代碼:經過優化的源文件生成擴展名為“pyo”,該類型的文件需要命令行工具生成。

在命令行中輸入“python2.7 -O -m py_compile ps.py”生成文件為ps.pyo而

"python3.5 -O -m py_compile ps.py"生成的文件為ps.pyc

 

類的私有變量、私有方法以兩個下划線作為前綴。

class Student:                 #類名首字母大寫

   __name=""                  #私有實例變量前必須有2個下划線

   def __init__(self,name):   #構造函數

       self.__name=name       #self相當於Java中的this

   

   def getName(self):         #方法名首字母小寫,其后每個單詞的首字母用大寫

       return self.__name

 

   def __del__(self):         #析構函數

       self.__name=None

 

if __name__=="__main__":

   student=Student("borphi")  #對象名用小寫字母

   print(student.getName())

注:python對代碼縮進的要求非常嚴格。如果程序中不采用代碼縮進的編碼風格,將拋出一個IndentationError異常。    

   

模塊是類或函數的集合,用於實現某個功能。在Python中,如果需要在程序中調用標准庫或其他第三方庫的類時,需要先使用import或from ... import語句導入相關的模塊。

1、import語句    如:import sys

2、from ... import ...:導入模塊指定的類或函數。  如:from sys import path

 

函數之間或類的方法之間用空行分隔,表示一段新的代碼的開始。與縮進不同,空行並不是python語法的一部分。只是為增加程序可讀性而已。

 

python以“#”作為注釋,特殊的注釋有:

1、中文注釋     #-*-coding:UTF-8-*-

2、跨平台注釋    #! /usr/bin/python

 

python也支持分號,但可以省略,python主要通過換行來識別語句的結束。python同樣支持多行寫一條語句,使用“\”作為換行符。

如:

sql="select id,name" \

   "from dept" \

   "where name='A"

 

局部變量是只能在函數或代碼段內使用的變量。python並沒有提供定義常量的保留字。

 

python中的字符串,可以用單引號、雙引號和三引號來包括。其中三引號保持字符原樣輸出,不做任何處理(占位符除外)。

 

python內置的幾種數據結構:元組、列表、字典和序列。

1、元組(Tuple):元組由不同的元素組成,每個元素可以存儲不同類型的數據,元組是“寫保護”的,即元組創建后不能再做任何修改操作,也不能添加或刪除任何元素。元組通常代表一行數據,而元組中的元素代表不同的數據項。tuple_name=(元素1,元素2,...)元組的訪問可以通過索引訪問。

元組的遍歷需要用到range()和len()這兩個函數

tuple=(("apple","banana"),("grape","orange"),("watermelon",),("grapefruit",))

for i in range(len(tuple)):

   print("tuple[%d]:"%i,"")

   for j in range(len(tuple[i])):

       print(tuple[i][j], "")

2、列表(List):通常作為函數的返回類型,可以實現添加(append())、刪除(remove())和查找(index())操作,元素的值可以被修改。list_name=[元素1,元素2,...]

list0=["apple","banana","grape","orange"]

list0.append("watermelon")

list0.insert(1,"grapefruit")

list0.remove("banana")      #如果列表中存在2個相同的元素,只刪除位置靠前的。

print(list0.pop())

print(list0[-2])

print(list0[1:3])

print(list0[-3:-1])

print(list0.index("grape"))

print("orange" in list0)

list0.sort()

list0.reverse()

 

list1=[["apple","banana"],["grape","orange"],["watermelon"],["grapefruit"]]

for i in range(len(list1)):

   print("list[%d]:"%i,"")

   for j in range(len(list1[i])):

       print(list1[i][j])

 

list0.extend(list1)

list0=list0+list1

list3=["apple","banana"]*2

print(list3)

注:用列表可以實現堆棧(append()、pop())和隊列(append()、pop(0))

3、字典(Dictionary):字典是由“鍵-值”對組成的集合,字典中的“值”通過“鍵”來引用。dictionary_name={key1:value1,key2:value2, ... }

注意:字典的書寫順序不是字典實際存儲順序,字典根據每個元素的Hashcode值進行排列。

dict={"a":"apple","b":"banana","g":"grape","o":"orange"}  #創建

dict["w"]="watermelon"   #添加

del(dict["a"])           #刪除

dict["g"]="grapefruit"   #修改

print(dict.pop("b"))

dict.clear()

#字典的遍歷

for k in dict:

   print("dict[%s]="%k,dict[k])

print(dict.items())#返回由元組組成的列表

for (k,v) in dict.items():

   print("dict[%s]="%k,v)

print(dict.keys())#輸出key的列表

print(dict.values())#輸出value的列表

4、序列:具有索引和切片能力的集合,元組、列表和字符串都屬於序列。

 

包、模塊、函數

python的程序由包(package)、模塊(module)和函數組成。包是一系統模塊組成的集合。模塊是處理某一類問題的函數和類的集合。

包是一個完成特定任務的工具箱,python提供了許多有用的工具包,如字符串處理、圖形用戶接口、Web應用、圖形圖像處理等。

注意:包必須至少含有一個__init__.py文件,該文件內容可以為空。__init__.py用於標識當前文件夾是一個包。

1、模塊把一組相關的函數或代碼組織到一個文件中。一個Python文件即是一個模塊。模塊由代碼、函數或類組成。

當python導入一個模塊時,python首先查找當前路徑,然后查找lib目錄、site-package目錄(python\lib\site-packages)和環境變量PYTHONPATH設置的目錄。

 

模塊導入

import 模塊名

導入模塊一次與多次的意義是一樣的。

重新導入:hello=reload(hello)

如果不想在程序中使用前綴符,可以使用from ... import ...語句將模塊導入。

from module_name import function_name

將函數存儲在被稱為模塊的獨立文件中, 再將模塊導入到主程序中。import語句允許在當前運行的程序文件中使用模塊中的代碼。

通過將函數存儲在獨立的文件中,可隱藏程序代碼的細節,將重點放在程序的高層邏輯上。將函數存儲在獨立文件中后,可與其他程序員共享這些文件而不是整個程序。

導入整個模塊

要讓函數是可導入的,得先創建模塊。模塊 是擴展名為.py的文件,包含要導入到程序中的代碼。

import pizza

Python讀取這個文件時,代碼行import pizza讓Python打開文件pizza.py,並將其中的所有函數都復制到這個程序中。

只需編寫一條import 語句並在其中指定模塊名,就可在程序中使用該模塊中的所有函數。如果你使用這種import 語句導入了名為module_name.py 的整個模塊,就可使用下面的語法來使用其中任何一個函數: module_name.function_name()

導入特定的函數

from module_name import function_name

通過用逗號分隔函數名,可根據需要從模塊中導入任意數量的函數:

from module_name import function_0, function_1, function_2

使用as 給函數指定別名

如果要導入的函數的名稱可能與程序中現有的名稱沖突,或者函數的名稱太長,可指定簡短而獨一無二的別名 ——函數的另一個名稱,類似於外號。要給函數指定這種特殊外 號,需要在導入它時這樣做。

from pizza import make_pizza as mp

使用as 給模塊指定別名

還可以給模塊指定別名。通過給模塊指定簡短的別名(如給模塊pizza 指定別名p ),讓你能夠更輕松地調用模塊中的函數。

import pizza as p

p.make_pizza(16, 'pepperoni')

導入模塊中的所有函數

使用星號(* )運算符可讓Python導入模塊中的所有函數:

from pizza import *

make_pizza(16, 'pepperoni')

import 語句中的星號讓Python將模塊pizza中的每個函數都復制到這個程序文件中。由於導入了每個函數,可通過名稱來調用每個函數,而無需使用句點表示法。

最佳的做法是,要么只導入你需要使用的函數,要么導入整個模塊並使用句點表示法。這能讓代碼更清晰,更容易閱讀和理解。 

 

模塊的屬性

模塊有一些內置屬性,用於完成特定的任務,如__name__、__doc__。每個模塊都有一個名稱。例如,__name__用於判斷當前模塊是否是程序的入口,如果當前程序正在被使用,__name__的值為“__main__”。通常給每個模塊都添加一個條件語句,用於單獨測試該模塊的功能。例如,創建一個模塊myModule:

if __name__=="__main__":

   print("myModule作為主程序運行")

else:

   print("myModule被另一個模塊調用")

__doc__可以輸出文檔字符串的內容。

 

模塊內置函數:

1、apply():可以實現調用可變參數列表的函數,把函數的參數存放在一個元組或序列中。

   apply(func [,args [,kwargs]])

2、filter():可以對某個序列做過濾處理,對自定義函數的參數返回的結果是否為“真”來過濾,並一次性返回處理結果

   filter(func or None,sequence) -> list, tuple, or string

3、reduce():對序列中元素的連續操作可以通過循環來處理。

   reduce(func,sequence[,initial])->value

4、map():多個序列的每個元素都執行相同的操作,並組成列表返回。

   map(func,sequence[,sequence, ...]) ->list

 

2、自定義包

包就是一個至少包含__init__.py文件的文件夾。例如,定義一個包parent,parent包中包含2個子包pack和pack2。pack包中包含myModule模塊,pack2包中包含myModule2模塊。

pack包的__init__.py

__all__=["myModule"]    #用於記錄當前包所包含的模塊,如果模塊多於2個,用逗號分開。這樣就可在調用時一次導入所有模塊

if __name__=="__main__":

    print("作為主程序運行")

else:

    print("pack初始化")

pack包的myModule.py

def func():

    print("pack.myModule.func()")

 

if __name__=="__main__":

    print("myModule作為主程序運行")

else:

    print("myModule被另一個模塊調用")

pack2包__init__.py

__all__=["myModule2"]   #用於記錄當前包所包含的模塊,如果模塊多於2個,用逗號分開。這樣就可在調用時一次導入所有模塊

if __name__=="__main__":

  print("作為主程序運行")

else:

  print("pack2初始化")

包pack2的myModule2:

def func():

  print("pack2.myModule.func2()")

 

if __name__=="__main__":

  print("myModule2作為主程序運行")

else:

  print("myModule2被另一個模塊調用")

parent模塊調用:

from pack import *

from pack2 import *

 

myModule.func()

myModule2.func2()

 

3、函數

定義:

def 函數名(參數1[=默認值1],參數2[=默認值2] ...):

  ...

  return 表達式

調用:

函數名(實參1, 實參2, ...)

注意:實參必須與形參一一對應,如果參數提供默認值,順序可以不一致。

位置實參 :調用函數時,Python必須將函數調用中的每個實參都關聯到函數定義中的一個形參。為此,最簡單的關聯方式是基於實參的順序。

def describe_pet(animal_type, pet_name):

     """顯示寵物的信息"""

     print("\nI have a " + animal_type + ".")

     print("My " + animal_type + "'s name is " + pet_name.title() + ".")

describe_pet('hamster', 'harry')

關鍵字實參:是傳遞給函數的名稱—值對。你直接在實參中將名稱和值關聯起來了,因此向函數傳遞實參時不會混淆(不會得到名為Hamster的harry這樣的結果)。關鍵字實參讓你無需考慮函數調用中的實參順序,還清楚地指出了函數調用中各個值的用途。

def describe_pet(animal_type, pet_name):

     """顯示寵物的信息"""

     print("\nI have a " + animal_type + ".")

     print("My " + animal_type + "'s name is " + pet_name.title() + ".")

describe_pet(animal_type='hamster', pet_name='harry') 

默認值

def describe_pet(pet_name, animal_type='dog'):

      """顯示寵物的信息"""

      print("\nI have a " + animal_type + ".")

      print("My " + animal_type + "'s name is " + pet_name.title() + ".")

describe_pet(pet_name='willie')

禁止函數修改列表

function_name(list_name[:]) #要將列表的副本傳遞給函數 

傳遞任意數量的實參

def make_pizza(*toppings):

       """打印顧客點的所有配料"""

       print(toppings)

make_pizza('pepperoni')

make_pizza('mushrooms', 'green peppers', 'extra cheese')

使用任意數量的關鍵字實參

def build_profile(first, last, **user_info):

      """創建一個字典,其中包含我們知道的有關用戶的一切"""

      profile = {}

      profile['first_name'] = first

      profile['last_name'] = last 

      for key, value in user_info.items():

            profile[key] = value

      return profile

user_profile = build_profile('albert', 'einstein', location='princeton',field='physics')

print(user_profile)

說明:形參**user_info 中的兩個星號讓Python創建一個名為user_info 的 空字典,並將收到的所有名稱—值對都封裝到這個字典中。

 

在函數中為了獲得對全局變量的完全控制(主要用於修改全局變量),需要使用關鍵字global。 

python中的任何變量都是對象,所以參數只支持引用傳遞的方式。即形參和實參指向內存的同一個存儲空間。

python不僅支持函數體內的嵌套,還支持函數定義的嵌套。

函數嵌套的層數不宜過多,就控制在3層以內。

# 嵌套函數

def func():

   x=1

   y=2

   m=3

   n=4

   def sum(a,b):   # 內部函數

       return a+b

   def sub(c,d):   # 內部函數

       return c-d

   return sum(x,y)*sub(m,n)

print(func())

注意:盡量不要在函數內部定義函數。

lambda函數

lambda函數用於創建一個匿名函數。

func=lambda  變量1, 變量1, ... : 表示式

調用:func()

# lambda

def func():

   x=1

   y=2

   m=3

   n=4

   sum=lambda a,b:a+b

   sub=lambda c,d:c-d

   return sum(x,y) * sub(m,n)

print(func())

注意:lambda也稱之為表達式,只能使用表達式,不能使用判斷、循環等多重語句。

Generator函數

生成器(Generator)的作用是一次產生一個數據項,並把數據項輸出。可以用在for循環中遍歷。Generator函數所具有的每次返回一個數據項的功能,使得迭代器的性能更佳。定義如下:

def 函數名(參數列表):

   ...

   yield 表達式

Generator函數的定義與普通函數的定義沒有什么區別,只要在函數體內使用yield生成數據項即可。

Generator函數可以被for循環遍歷,而且可以通過next()方法獲得yield生成的數據項。

# 定義Generator函數

def func(n):

    for i in range(n):

       yield i

    #for循環中輸出

    for i in func(3):

       print(i)

#使用next()輸出

r=func(3)

print(r.__next__())

print(r.__next__())

print(r.__next__())

注意:yield保留字與return語句的返回值和執行原理並不相同。yield生成值並不會中止程序的執行,返回值繼續往后執行。return返回值后,程序將中止執行。

 

字符串

1、字符串格式化

Python將若干值插入到帶“%”標記的字符串中,語法如下

"%s" % str1

"%s %s"% (str1,str2)

注意:如果要格式化多個值,元組中元素的順序必須和格式化字符串中替代符的順序一致。

Python格式化字符串的替代符及其含義

注意:如果要在字符串中輸出“%”,則需要使用“%%”。

2、字符串的轉義符

Python中轉義字符的用法與Java相同,都是使用“\”作為轉義字符。

Python的轉義字符及其含義

注意:如果要在字符串中輸出"\",需要使用“\\”

3、字符串合並

Python使用“+”連接不同的字符串,如果兩側都是字符串,執行連接操作,如果兩側都是數字類型,則執行加法運算;如果兩側類型不同,則拋出異常:TypeError

4、字符串的截取

Python字符串內置了序列,可以通過“索引”、“切片”獲取子串,也可以使用函數split來獲取。

切片的語法格式如下所示:string[start:end:step]

5、字符串的比較

Python直接使用“==”、“!=”運算符比較兩個字符串的內容。startswith()、endswith()

6、字符串反轉

Python使用列表和字符串索引來實現字符串的反轉,並通過range()進行循環。

# 循環輸出反轉的字符串

def reverse(s):

   out=""

   li=list(s)

   for i in range(len(li),0,-1):

      out+="".join(li[i-1])

   return out

利用序列的“切片”實現字符串反轉最為簡潔:

# 循環輸出反轉的字符串

def reverse(s):   

    return s[::-1]

7、字符串的查找和替換

查找:find()、rfind()

替換:replace():不支持正則

8、字符串與日期轉換

Python提供了time模塊處理日期和時間

從時間到字符串的轉換strftime(),格式:strftime(format[,tuple])->string

格式化日期常用標記

字符串到日期的轉換:需要進行兩次轉換,使用time模塊和datetime類。轉換過程分為3個步驟。

(1)、調用函數strptime()把字符串轉換為一個元組,進行第一次轉換,格式如下

            strptime(string,format)->struct_time

(2)、把表示時間的元組賦值給表示年、月、日的3個變量

(3)、把表示年、月、日的3個變量傳遞給函數datetime(),進行第2次轉換,格式如下

            datetime(year,month,day[,hour[,minute[,second[,microsecond[,tzinfo]]]])

正則表達式

1、基礎

正則表達式中的特殊字符

正則表達式中的常用限定符

限定符與“?”的組合

2、使用syt.re模塊處理正則表達式

re模塊的規則選項

pattern對象的屬性和方法

match對象的方法和屬性

 

類與對象

1、類

定義:

class Fruit:

   def grow(self):   #類的方法必須有1self參數,但是方法調用時可以不傳這個參數

      print("Fruit grow ...")

      if __name__=="__main__":

fruit=Fruit()

fruit.grow()

2、對象的創建

if __name__=="__main__":

    fruit=Fruit()

    fruit.grow()

屬性和方法

1、python類的屬性分為私有屬性和公有屬性,但python並沒有提供公有屬性和私有屬性的修飾符。類的私有屬性不能被該類之外的函數調用,類屬性的作用范圍完全取決於屬性的名稱。如果函數、方法或屬性的名字以兩個下划線開始,則表示私有類型;沒有使用兩個下划線開始則表示公有屬性。

python的屬性分為實例屬性和靜態屬性。實例屬性是以self作為前綴的屬性。__init__方法即Python類的構造函數。如果__init__方法中定義的變量沒有使用self作為前綴聲明,則該變量只是普通的局部變量。在python中靜態變量稱之為靜態屬性。

class Fruit:

   price=0                  #類屬性

   def __init__(self):

      self.color="red"     #實例屬性

      zone="China"         #局部變量

 

if __name__=="__main__":

   print(Fruit.price)

   apple=Fruit()

   print(apple.color)

   Fruit.price=Fruit.price+10

   print("apple's price:"+str(apple.price))

   banana=Fruit()

   print("banana's price:" + str(banana.price))

注意:Python的類和對象都可以訪問類屬性。

python提供了直接訪問私有屬性的方式,可用於程序的測試和調試,訪問的格式如下:

instance_classname_attribute     #instance表示對象;classname表示類名;attribute表示私有屬性。

class Fruit:

    def __init__(self):

        self.__color="red"     #私有屬性

 

if __name__=="__main__":

    apple=Fruit()

    print(apple._Fruit__color)

類提供了一些內置屬性,用於管理類的內部關系。如,__dict__、__bases__、__doc__等

2、類的方法

類的方法也分為公有方法和私有方法。私有函數不能被該類之外的函數調用,私有方法也不能被外部的類或函數調用。Python使用函數staticmethod()或"@staticmethod"指令的方式把普通函數轉換為靜態方法。Python的靜態方法並沒有和類的實例進行名稱綁定,Python的靜態方法相當於全局函數。

class Fruit:

    price = 0

 

    def __init__(self):

        self.__color="red"     #私有屬性

    def getColor(self):

        print(self.__color)

 

    @staticmethod

    def getPrice():

   print(Fruit.price)

 

    def __getPrice():

       Fruit.price=Fruit.price+10

       print(Fruit.price)

 

    count=staticmethod(__getPrice)

 

if __name__=="__main__":

    apple=Fruit()

    apple.getColor()

    Fruit.count()

    banana = Fruit()

    Fruit.count()

    Fruit.getPrice()

Python中還有一種方法稱之為類方法。類方法的作用與靜態方法相似,都可以被其它實例對象共享,不同的是類方法必須提供self參數。類方法可以使用函數classmethod()或“@classmethod”指令定義。

class Fruit:

   price = 0

 

   def __init__(self):

      self.__color="red"     #私有屬性

   def getColor(self):

      print(self.__color)

 

   @classmethod

   def getPrice(self):

      print(self.price)

 

   def __getPrice(self):

      self.price=self.price+10

      print(self.price)

 

count=classmethod(__getPrice)

 

if __name__=="__main__":

   apple=Fruit()

   apple.getColor()

   Fruit.count()

   banana = Fruit()

   Fruit.count()

   Fruit.getPrice()

如果某個方法需要被其他實例共享,同時又需要使用當前實例的屬性,則將其定義為類方法。

3、內部類的使用

內部類中的方法可以使用兩種方法調用

第一種方法是直接使用外部類調用內部類,生成內部類的實例,再調用內部類的方法,調用格式如下所示:

object_name=outclass_name.inclass_name()

object_name.method()

第二種方法是先對外部類進行實例化,然后再實例化內部類,最后調用內部類

out_name=outclass_name()

in_name=out_name.inclass_name()

in_name.method()

內部類使用方法:

class Car:

class Door:               #內部類

       def open(self):          

print("open door")

class Wheel:              #內部類

       def run(self):

print("car run")

 

if __name__=="__main__":

car=Car()

backDoor=Car.Door()       #內部類的實例化方法一

frontDoor=car.Door()      #內部類的實例化方法二

backDoor.open()

frontDoor.open()

wheel=Car.Wheel()

wheel.run()

4、__init__方法

python的構造函數名為__init__。__init__方法除了用於定義實例變量外,還用於程序的初始化。__init__方法是可選的,如果不提供__init__方法,Python將會給出一個默認的__init__方法。

5、__del__方法

Python提供了析構函數__del__()。析構函數可以顯式的釋放對象占用的資源,析構函數也是可選的,如果程序不提供析構函數,Python會在后台提供默認的析構函數。

如果要顯式的調用析構函數,可以使用del語句,在程序的末尾添加如下語句

del fruit     #執行析構函數

6、垃圾回收機制

Python也采用垃圾回收機制清除對象,Python提供了gc模塊釋放不再使用的對象。垃圾回收的機制有許多種算法,Python采用的是引用計算的方式。函數collect()可以一次性收集所有待處理的對象。

import gc

 

class Fruit:

    def __init__(self,name,color):     #初始化name,color屬性

       self.__name=name

       self.__color=color

    def getColor(self):

       return self.__color

    def setColor(self,color):

       self.__color=color

    def getName(self):

       return self.__name

    def setName(self,name):

       self.__name=name

 

class FruitShop:                       #水果店類

    def __init__(self):

       self.fruits=[]

    def addFruit(self,fruit):          #添加水果

       fruit.parent=self              #把Fruit類關聯到FruitShop類

       self.fruits.append(fruit)

 

if __name__=="__main__":

    shop=FruitShop()

    shop.addFruit(Fruit("apple","red"))

    shop.addFruit(Fruit("banana", "yellow"))

    print(gc.get_referents(shop))

    del shop

    print(gc.collect())                 #顯式調用垃圾回收器

7、類的內置方法

__new__()

__new__()在__init__()之前調用,用於生成實例對象。利用這個方法和類屬性的特性可以實現設計模式中的單例模式。

class Singleton(object):

   __instance=None           #定義實例

   

   def __init__(self):

      pass

   def __new__(cls, *args, **kwargs):    #在__init__之前調用

       if Singleton.__instance is None:  #生成唯一實例

           Singleton.__instance=object.__new__(cls,*args,**kwargs)

       return Singleton.__instance

8、方法的動態特性

Python作為動態腳本語言,編寫的程序具有很強的動態性。可以動態添加類的方法,把某個已經定義的函數添加到類中。添加新方法的語法格式如下所示:

class_name.method_name=function_name

注意:function_name表示一個已經存在的函數

class Fruit:

    pass

def add(self):

    print("grow ...")

 

if __name__=="__main__":

    Fruit.grow=add()

    fruit=Fruit()

    fruit.grow()

繼承

Python不提倡過度包裝。繼承可以重用已經存在的數據和行為,減少代碼的重復編寫。Python在類名后使用一對括號表示繼承關系,括號中的類即為父類。如果父類定義了__init__方法,子類必須顯式調用父類的__init__方法。如果子類需要擴展父類的行為,可以添加__init__方法的參數。

class Fruit():

   def __init__(self,color):

  self.color=color

  print("fruit's color:%s"%self.color)

   def grow(self):

  print("grow ...")

 

class Apple(Fruit):

   def __init__(self,color):

  Fruit.__init__(self,color)

  print("apple's color:%s"%self.color)

 

class Banana(Fruit):

   def __init__(self,color):

  Fruit.__init__(self,color)

  print("banana's color:%s"%self.color)

   def grow(self):

  print("banana grow ...")

 

if __name__=="__main__":

   apple=Apple("red")

   apple.grow()

   banana=Banana("yellow")

   banana.grow()

還可以使用super類的super()調用父類的__init__方法。super()可以綁定type類的父類。

super(type,obj)

class Fruit(object):

  def __init__(self):

    print("parent")

 

class Apple(Fruit):

  def __init__(self):

    super(Apple, self).__init__()

    print("apple child")

 

if __name__=="__main__":

  Apple()

注意:super類的實現代碼繼承了object,因此Fruit類必須繼承object.如果不繼承object,使用super()將出現錯誤。

python沒有提供對接口的支持。

運算符的重載

Python把運算符和類的內置方法關聯起來,每個運算符都對應1個函數。

class Fruit:

  def __init__(self,price=0):

    self.price=price

  def __add__(self, other):             #重載加號運算符

          return self.price+other.price

  def __gt__(self, other):              #重載大於運算符

         if self.price>other.price:

      flag=True

         else:

      flag=False

         return flag

 

class Apple(Fruit):

  pass

class Banana(Fruit):

  pass

python工廠方法模式

工廠方法類圖

實現方法

class Factory:                         #工廠類

   def createFruit(self,fruit):       #工廠方法

       if fruit=="apple":

return Apple()

  elif fruit=="banana":

     return Banana()

 

class Fruit:

  def __str__(self):

    return "fruit"

 

class Apple(Fruit):

  def __str__(self):

    return "apple"

 

class Banana(Fruit):

  def __str__(self):

    return "banana"

 

if __name__=="__main__":

  factory=Factory()

  print(factory.createFruit("apple"))

  print(factory.createFruit("banana"))

 

異常處理與程序調試

Python中的異常類定義在exceptions模塊中,並繼承自基類BaseException。BaseException類是屬於new-style class,BaseException類下有3個子類,分別是Exception、KeyboardInterrupt、SystemExit。

Exception類是最常用的異常類,該類包括StandardError、StopIteration、GeneratorExit、Warning等異常類。

BaseException
 +-- SystemExit
 +-- KeyboardInterrupt
 +-- GeneratorExit
 +-- Exception
      +-- StopIteration
      +-- StopAsyncIteration
      +-- ArithmeticError
      |    +-- FloatingPointError
      |    +-- OverflowError
      |    +-- ZeroDivisionError
      +-- AssertionError
      +-- AttributeError
      +-- BufferError
      +-- EOFError
      +-- ImportError
      +-- LookupError
      |    +-- IndexError
      |    +-- KeyError
      +-- MemoryError
      +-- NameError
      |    +-- UnboundLocalError
      +-- OSError
      |    +-- BlockingIOError
      |    +-- ChildProcessError
      |    +-- ConnectionError
      |    |    +-- BrokenPipeError
      |    |    +-- ConnectionAbortedError
      |    |    +-- ConnectionRefusedError
      |    |    +-- ConnectionResetError
      |    +-- FileExistsError
      |    +-- FileNotFoundError
      |    +-- InterruptedError
      |    +-- IsADirectoryError
      |    +-- NotADirectoryError
      |    +-- PermissionError
      |    +-- ProcessLookupError
      |    +-- TimeoutError
      +-- ReferenceError
      +-- RuntimeError
      |    +-- NotImplementedError
      |    +-- RecursionError
      +-- SyntaxError
      |    +-- IndentationError
      |         +-- TabError
      +-- SystemError
      +-- TypeError
      +-- ValueError
      |    +-- UnicodeError
      |         +-- UnicodeDecodeError
      |         +-- UnicodeEncodeError
      |         +-- UnicodeTranslateError
      +-- Warning
           +-- DeprecationWarning
           +-- PendingDeprecationWarning
           +-- RuntimeWarning
           +-- SyntaxWarning
           +-- UserWarning
           +-- FutureWarning
           +-- ImportWarning
           +-- UnicodeWarning
           +-- BytesWarning
           +-- ResourceWarning

StandardError類中常見的異常

Python使用try ... exception語句捕獲異常,異常類型定義在try子句的后面。

注意:如果在except子句后將異常類型設置為"Exception",異常處理程序將捕獲除程序中斷外的所有異常,因為Exception類是其他異常類的基類。

try ... exception用法:

try:

  file("hello.txt",'r')

  print('讀文件')

except IOError:

  print("文件不存在")

except:

  print("程序異常")

else:

  print("結束")

try ... finally用法

try:

  f=file("hello.txt",'r')

  print('讀文件')

except IOError:

  print("文件不存在")

finally:

  f.close()

 

使用raise拋出異常

可以通過raise語句顯式引發異常。一旦執行了raise語句,raise語句后的代碼將不能被執行。

try:

   s=None

   if s is None:

       print("s 是空對象")

       raise NameError

   print(len(s))

except TypeError:

   print("空對象沒有長度")    

 

自定義異常

自定義異常必須繼承Exception類,自定義異常按照命名規范以"Error"結尾,使用raise引發,且只能通過手工方式觸發

from __future__ import division

 

class DivisionException(Exception):

   def __init__(self,Exception):

       Exception.__init__(self,x,y)

       self.x=x

       self.y=y

 

if __name__=="__main__":

   try:

       x=3

       y=2

       if x%y>0:

           print(x/y)

           raise DivisionException(x,y)

   except DivisionException as div:

       print("DivisionException:x/y=%.2f"%(div.x/div.y))

 

assert語句的使用 

assert語句用於檢測某個條件表達是否為真,又稱斷言語句  

t=("hello")

assert len(t)>=1

注意:python支持形如"m<=x<=n"的表達式。

 

Python中的traceback對象可記錄異常信息和當前程序的狀態。當異常發生時,traceback對象將輸出異常信息。異常信息應從下往上閱讀。

 

python的數據庫編程

Python提供了連接數據庫的專用模塊,不同的數據庫可以使用相應的專用模塊訪問數據庫。

1、cx_Oracle模塊

python的cx_Oracle模塊可以訪問Oracle數據庫。

cx_Oracle模塊的下載地址:http://cx-oracle.sourceforge.net/

代碼示例:

import cx_Oracle

connection=cx_Oracle.Connection("scott","tiger,","ORCL") #連接oracle數據庫

cursor=connection.cursor()   #獲取cursor對象操作數據庫

sql="";

cursor.execute(sql)

for x in cursor.fetvchall():

  for value in x:

    print(value)

cursor.close()

connection.close()

2、MySQLdb模塊

MySQLdb模塊是python操作MySQL數據庫的。

代碼示例

import os,sys

import MySQLdb

#連接數據庫

try:

  conn=MySQLdb.connect(host="localhost",user="root",passwd="",db="")

  cursor=conn.cursor()

  sql="insert into address(name,address) values (%s,%s)"

  values=(("張三","北京海淀區"),("李四","北京海淀區"),("王五","北京海淀區"))

  cursor.executemany(sql,values)   #插入多條數據

except Exception as e:

  print(e)

  sys.exit()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

try:

  sql=""

  cursor.execute(sql)                   #查詢數據

  data=cursor.fetchall()

  if data:

    for x in data:

      print(x[0],x[1])

  cursor.close()                        #關閉游標

  conn.close()                          #關閉數據庫

except Exception as e:

  print(e)

3、SQLite數據庫

#-*-coding:utf-8-*-

import sqlite3

#連接數據庫

conn=sqlite3.connect("./address.db")

#創建表

conn.execute("create table if not exists address(id integer primary key autoincrement,name VARCHAR(128),address VARCHAR (128))")

conn.execute("insert into address(name,address) VALUES ('Tom','Beijing road')")

conn.execute("insert into address(name,address) VALUES ('Jerry','Shanghai road')")

#手動提交數據

conn.commit()

#獲取游標對象

cur=conn.cursor()

#使用游標查詢數據

cur.execute("select * from address")

#獲取所有結果

res=cur.fetchall()

print "address:",res

for line in res:

  for f in line:

    print f

#關閉連接

cur.close()

conn.close()

 

Python的持久化模塊

python的標准庫提供了幾種持久化模塊。這些模塊可以模擬數據庫的操作,會把數據保存在指定的文件中。例如dbhash、anydbm、shelve等模塊。

1、dbhash模塊讀寫數據

DBM是一種文件式數據庫,采用哈希結構進行存儲。是一種簡單的數據庫,並不具備管理能力,但是比普通文件更穩定、可靠,而且查詢速度快。unix操作系統使用gdbm,而windows可以使用dbhash模塊。

window環境下DBM數據庫的讀寫操作

import  dbhash

db=dbhash.open('temp','c')    #創建並打開數據庫

db["Tom"]="Beijing road"      #寫數據

db["Jerry"]="Shanghai road"

for k,v in db.iteritems():    #遍歷db對象

   print(k,v)

if db.has_key("Tom"):

   del db["Tom"]

print(db)

db.close()                     #關閉數據庫

注意:dbhash模塊返回字典的key、value值只支持字符串類型

為了統一不同操作系統對DBM數據庫的要求,Python的anydbm模塊提供了操作DBM數據庫的一般性操作。其用法和dbhash模塊類似。

2、shelve模塊讀寫數據

shelve模塊是Python的持久化對象模塊,用法與anydbm模塊的用法相似,但是shelve模塊返回字典的value值支持基本的Python類型。

import  shelve

addresses=shelve.open('addresses')    #創建並打開數據庫

addresses["1"]=["Tom","Beijing road","2018-01-03"]      #寫數據

addresses["2"]=["Jerry","Shanghai road","2008-03-30"]

if addresses.has_key("2"):

    del addresses["2"]

print(addresses)

addresses.close()                     #關閉數據庫

注意:shelve模塊返回字典的key值只支持字符串類型

 

文件處理

文件通常用於存儲數據或應用程序的參數。Python提供了osos.pathshutil等模塊用於處理文件。其中包括打開文件、讀寫文件、復制和刪除文件等函數。

文件的處理一般分為以下3個步驟:

1)創建並打開文件,使用file()函數返回一個file對象。

file(name[, mode[, buffering]])

文件打開的模式(mode)

參數

說明

r

以只讀的方式打開文件

r+

以讀寫的方式打開文件

w

以寫入的方式打開文件。先刪除文件原有的內容,再重新寫入新的內容。如果文件不存在,則創建1個新的文件。

w+

以讀寫的方式打開文件。先刪除文件原有的內容,再重新寫入新的內容。如果文件不存在,則創建1個新的文件。

a

以寫入的方式打開文件,在文件的末尾追加新的內容。如果文件不存在,則創建1個新的文件.

a+

以讀寫的方式打開文件,在文件的末尾追加新的內容。如果文件不存在,則創建1個新的文件.

b

以二進制的模式打開文件。可與rw、a、+結合使用

U

支持所有的換行符號。"\r""\n","\r\n"都表示換行

注意:對於圖片、視頻等文件必須使用"b"的模式讀寫

2)調用file對象的read()、write()等方法處理文件。

3)調用close()關閉文件,釋放file對象占用的資源。

示例:

#創建文件

context='''helloworld

hellochina

'''

f=open('hello.txt','w')#打開文件

f.write(context)#把字符串寫入文件

f.close()#關閉文件

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#按行讀取方式:使用readline()讀文件

f=open('hello.txt')

while True:

line=f.readline()

if line:

  print(line)

else:

  break

f.close()

 

#多行讀取方式:使用readlins()讀文件

f=open('hello.txt')

lines=f.readlines()

for line in lines:

  print(line)

f.close()

 

#一次性讀取方式:read()

f=open('hello.txt')

context=f.read()

print(context)

f.close()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#使用writelines()寫文件

f=open('hello.txt','w+')

li=['helloworld\n','hellochina\n']

f.writelines(li)

f.close()

 

#使用write()寫文件:追加新的內容到文件

f=open('hello.txt','a+')

new_context="goodbye"

f.write(new_context)

f.close()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

文件的刪除需要使用os模塊和os.path模塊。os模塊提供了對系統環境、文件、目錄等操作的系統級的接口函數。

os模塊常用的文件處理函數

函數

說明

access(path,mode)

按照mode指定的權限訪問文件

chmod(path,mode)

改變文件的訪問權限,mode用UNIX系統中的權限代號表示

open(filename,flag[,mode=0777])

按照mode指定的權限打開文件,默認情況下,給所有用戶讀、寫、執行的權限

remove(path)

刪除path指定的文件

rename(old,new)

重命名文件或目錄,old表示原文件或目錄,new表示新文件或目錄

stat(path)

返回path指定文件的所有屬性

fstat(path)

返回打開的文件的所有屬性

lseek(fd,pos,how)

設置文件的當前位置,返回當前位置的字節數

startfile(filepath[,operation])

啟動關聯程序打開文件。例如,打開的是1html文件,將啟動瀏覽器

tmpfile()

創建1個臨時文件,文件創建在操作系統的臨時目錄中

os.path模塊常用的函數

函數

說明

abspath(path)

返回path所在的絕對路徑

dirname(p)

返回目錄的路徑

exists(path)

判斷文件是否存在

getatime(filename)

返回文件的最后訪問時間

getctime(filename)

返回文件的創建時間

getmtime(filename)

返回文件的最后修改時間

getsize(filename)

返回文件的大小

isabs(s)

測試路徑是否為絕對路徑

isdir(path)

判斷path指定的是否為目錄

isfile(path)

判斷path指定的是否為文件

split(p)

對路徑進行分割,並以列表的方式返回

splitext(p)

從路徑中分割文件的擴展名

splitdrive(p)

從路徑中分割驅動器的名稱

walk(top,func,arg)

遍歷目錄樹,與os.walk()的功能相同

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#刪除文件

importos

if os.path.exists('hello.txt'):

  os.remove('hello.txt')

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

file類沒有提供直接復制文件的方法,但是可以使用read(),write()方法模擬實現文件復制功能。

#使用read()、write()實現拷貝

#創建文件hello.txt

src=open('hello.txt','w')

li=['helloworld\n','hellochina\n']

src.writelines(li)

src.close()

#把hello.txt拷貝到hello2.txt

src=open('hello.txt','r')

dst=open('hello2.txt','w')

dst.write(src.read())

src.close()

dst.close()

 

shutil模塊是另一個文件、目錄的管理接口,提供了一些用於復制文件、目錄的函數。copyfile()函數可以實現文件的拷貝,copyfile()函數的聲明如下:

copyfile(src,dst)

文件的剪切可以使用move()函數模擬,該函數聲明如下:

move(src,dst)

#shutil模塊實現文件的拷貝、移動

import shutil

shutil.copyfile('hello.txt','hello2.txt')

shutil.move('hello.txt','../')

shutil.move('hello2.txt','hello3.txt')

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

os模塊的函數rename()可以對文件或目錄進行重命名。

#修改文件名

import os

li=os.listdir(".")

print(li)

if "hello.txt" in li:

  os.rename('hello.txt','hi.txt')

elif 'hi.txt' in li:

  os.rename('hi.txt','hello.txt')

 

#修改文件后綴(即擴展名)

import os

files=os.listdir('.')

for filename in files:

  pos=filename.find('.')

  if filename[pos+1:]=='html':

    newname=filename[:pos+1]+"htm"

    os.rename(filename,newname)

 

#修改文件后綴(即擴展名)--簡化版

import os

files=os.listdir('.')

for filename in files:

  li=os.path.splitext(filename)

  if li[1]==".html":

    newname=li[0]+".htm"

    os.rename(filename,newname)

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#文件的查找

import re

f1=open('hello.txt','r')

count=0

for s in f1.readlines():

  li=re.findall('hello',s)

  if len(li)>0:

    count+=li.count("hello")

  print("查找到"+str(count)+"個hello")

  f1.close()

 

#文件內容的替換

f1=open('hello.txt','r')

f2=open('hello2.txt','w')

for s in f1.readlines():

f2.write(s.replace("hello",'hi'))

f1.close()

f2.close()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

python提供了模塊difflib用於實現對序列、文件的比較。如果要比較2個文件,列出2個文件的異同,可以使用difflib模塊的SequenceMatcher類實現。其中get_opcodes()可以返回2個序列的比較結果。調用get_opcodes之前,需要先生成1SequenceMatcher對象。

#文件比較

import difflib

f1=open('hello.txt','r')

f2=open('hi.txt','r')

src=f1.read()

dst=f2.read()

print(src)

print(dst)

s=difflib.SequenceMatcher(lambda x:x=="",src,dst)

for tag,i1,i2,j1,j2 in s.get_opcodes():

   print("%ssrc[%d:%d]=%sdst[%d:%d]=%s"%(tag,i1,i2,src[i1:i2],j1,j2,dst[j1:j2]))

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

python標准庫ConfigParser模塊用於解析配置文件。ConfigParser模塊類可讀取ini文件的內容

ODBC.ini

[ODBC 32 bit Data Sources]

MS Access Database=Microsoft Access Driver(*.mdb)(32)

Excel Files=Microsoft Excel Driver(*.xls)(32)

dBASE Files=Microsoft dBase Driver(*.dbf)(32)

[MSAccessDatabase]

Driver32=C:\WINDOWS\system32\odbcjt32.dll

[ExcelFiles]

Driver32=C:\WINDOWS\system32\odbcjt32.dll

[dBASEFiles]

Driver32=C:\WINDOWS\system32\odbcjt32.dll

 

#讀取配置文件

import configparser

config=configparser.ConfigParser()

config.read("ODBC.ini")

sections=config.sections()#返回所有配置塊的標題

print("配置塊:",sections)

o=config.options("ODBC 32 bit Data Sources")#返回所有配置項的標題

print("配置項:",o)

v=config.items("ODBC 32 bit Data Sources")

print("內容:",v)

#根據配置塊和配置項返回內容

access=config.get("ODBC 32 bit Data Sources","Ms Access Database")

print(access)

excel=config.get("ODBC 32 bit Data Sources","Excel Files")

print(excel)

dBASE=config.get("ODBC 32 bit Data Sources","dBASE Files")

2、配置文件寫入

#寫入配置文件

import configparser

config=configparser.ConfigParser()

config.add_section("ODBC Driver Count")#添加新配置塊

config.set("ODBC Driver Count","count",2)#添加新的配置項

f=open("ODBC.ini",'a+')

config.write(f)

f.close()

config.read("ODBC.ini")

3、修改配置文件

#修改配置文件

import configparser

config=configparser.ConfigParser()

config.read("ODBC.ini")

config.set("ODBC Driver Count","count",3)#修改配置項

f=open("ODBC.ini","r+")

config.write(f)

f.close()

4、刪除配置塊和配置項

#刪除配置塊和配置項

import configparser

config=configparser.ConfigParser()

config.read("ODBC.ini")

config.remove_option("ODBC Driver Count","count")#刪除配置項

config.remove_section("ODBC Driver Count")#刪除配置塊

f=open("ODBC.ini","w+")

config.write(f)

f.close()

 

目錄的基本操作

os模塊提供了針對目錄進行操作的函數

函數

說明

mkdir(path[,mode=0777])

創建path指定的1個目錄(一次只能創建一個目錄)

makedirs(name,mode=511)

創建多級目錄,name表示為 "path1/path2/..."一次可以創建多個目錄

rmdir(path)

刪除path指定的目錄(一次只能刪除一個)

removedirs(path)

刪除path指定的多級目錄(一次可以刪除多個目錄)

listdir(path)

返回path指定目錄下所有的文件名

getcwd()

返回當前的工作目錄

chdir(path)

將當前目錄改變為path指定的目錄

walk(top,topdown=True,onerror=None

遍歷目錄樹

 

import os

os.mkdir("hello")

os.rmdir("hello")

os.makedirs("hello/world")

os.removedirs("hello/world")

 

目錄的遍歷有3種實現方法--遞歸函數、os.path.walk()、os.walk()

#1、遞歸遍歷目錄

import os

def visitDir(path):

  li=os.listdir(path)

  for p in li:

    pathname=os.path.join(path,p)

    if not os.path.isfile(pathname):

      visitDir(pathname)

    else:

      print(pathname)

 

if__name__=="__main__":

  path=r"/Users/liudebin/資料"

  visitDir(path)

 

#2os.path.walk()

import os,os.path

def visitDir(arg,dirname,names):

  for filepath in names:

    print(os.path.join(dirname,filepath))

 

if__name__=="__main__":

  path=r"/Users/liudebin"

  os.path.walk(path,visitDir,())

 

#3os.walk

def visitDir(path):

  for root,dirs,files in os.walk(path):

    for filepath in files:

      print(os.path.join(root,filepath))

 

if__name__=="__main__":

  path=r"/Users/liudebin"

  visitDir(path)

 

注意:os.path.walk()os.walk()產生的文件名列表並不相同:

os.path.walk()產生目錄樹下的目錄路徑和文件路徑,而os.walk()只產生文件路徑

 

文件和流

python隱藏了流的機制,在python的模塊中找不到類似Stream類,python把文件的處理和流關聯在一起,流對象實現了File類的所有方法。sys模塊提供了3種基本的流對象---stdinstdoutstderr。流對象可以使用File類的屬性和方法,流對象的處理和文件的處理方式相同。

1、stdin

importsys

sys.stdin=open('ODBC.ini','r')

for line in sys.stdin.readlines():

  print(line)

2、stdout

importsys

sys.stdout=open(r'ODBC.ini','a')

print("goodbye")

sys.stdout.close()

3、stderr

import sys,time

sys.stderr=open('record.log','a')

f=open(r"./hello.txt","r")

t=time.strftime("%Y-%m-%d%X",time.localtime())

context=f.read()

if context:

  sys.stderr.write(t+""+context)

else:

  raise Exception(t+"異常信息")

 

python模擬Java輸入、輸出流

#文件輸入流

def fileInputStream(filename):

  try:

    f=open(filename)

    for line in f:

      for byte in line:

        yield byte

  except StopIteration:

    f.close()

  return

 

#文件輸出流

def fileOutputStream(inputStream,filename):

  try:

    f=open(filename,'w')

    while True:

      byte=inputStream.next()

      f.write(byte)

  except StopIteration:

    f.close()

  return

 

if__name__=="__main__":

  fileOutputStream(fileInputStream('hello.txt'),'hello2.txt')

 

示例:

#文件屬性瀏覽

def showFileProperties(path):

  """顯示文件的屬性,包括路徑、大小、創建日期,最后修改時間,最后訪問時間"""

  import time,os

  for root,dirs,files in os.walk(path,True):

    print("位置:"+root)

    for filename in files:

      stats=os.stat(os.path.join(root,filename))

      info="文件名:"+filename+""

      info+="大小:"+("%dM"%(stats[-4]/1024/1024))+""

      t=time.strftime("%Y-%m-%d%X",time.localtime(stats[-1]))

      info+="創建時間:"+t+""

      t=time.strftime("%Y-%m-%d%X",time.localtime(stats[-2]))

      info+="最后修改時間:"+t+""

      t=time.strftime("%Y-%m-%d%X",time.localtime(stats[-3]))

      info+="最后訪問時間:"+t+""

      print(info)

 

if __name__=="__main__":

  path=r"/Users/liudebin/Downloads/第一二期/第二期"

  showFileProperties(path)

 

注意:os.stat()的參數必須是路徑

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

URL的解析

Python中用來對URL字符串進行解析的模塊是urlparse。該模塊主要的方法有urlparse、urljoin、urlsplit和urlunsplit等

在Python語言中,urlparse對於URL的定義采用的六元組,如下所示:

scheme://netloc/path;parameters?query#fragment

urlparse方法返回對象的屬性

 

可以使用PyChecker和PyLine檢查源代碼。

使用Distutils可以讓開發者輕松地用Python編寫安裝腳本。

日志記錄可以使用標准庫中的logging模塊,基本用法很簡單:

import logging

logging.basicConfig(level=logging.INFO,filename='mylog.log')

logging.info("Starting program")

logging.info("Trying to divide 1 by 0")

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

測試

在Python中代碼測試包含兩種類型:unittestdoctest

unittest模塊:用來寫PyUnit的測試代碼。支持對軟件代碼的自動化測試。

doctest模塊:可以直接在代碼的注釋中寫測試用例。此模塊將測試用例內置在了函數的文檔字符串,從而達到了文檔和測試代碼的統一。

TDD(測試驅動開發):基本思想是測試先行,在開發具體的功能代碼之前,需要先編寫此功能的測試代碼。只有通過了測試的代碼,才能夠加入到代碼倉庫中。

#encoding=utf-8

importunittest

importstring

class StringReplaceTestCase1(unittest.TestCase):

  """測試空字符串替換"""

  def runTest(self):

    src="HELLO"

    exp="HELLO"

    result=string.replace(src,"","")

    self.assertEqual(exp,result)

 

srtc=StringReplaceTestCase1()

srtc.runTest()

在python語言中,可以用內置的assert語句來實現測試用例運行時候的斷言。

unittest模塊中的測試方法

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM