這篇內(nèi)容其實很早就在自己的電腦上整理完成了边灭,主要用作對做記錄整理Python和其他語言不太一樣的地方澜薄,使自己可以快速回顧Python知識,使用Python证逻。如果你學(xué)習(xí)過Python但平時不常用Python香椎,或許也可以試著參考一下漱竖。(內(nèi)容是由簡入深的,但是現(xiàn)在看來顯得有些混亂畜伐,不夠系統(tǒng))
內(nèi)容摘要
- 語言基本內(nèi)容(語句馍惹、數(shù)組等)
- 面向?qū)ο?/li>
- Python魔術(shù)方法
- 生命周期
- 正則
- 其他內(nèi)容(Python之禪、打包等)
語言基本內(nèi)容
運算符:
- **即求平方玛界。
- //地板除即去掉小數(shù)部分万矾。
- /傳統(tǒng)除法,整數(shù)地板除慎框,浮點數(shù)精確除良狈。
字符串:
- 三引號,多行文本笨枯,可以不用寫
\n
- 可以使用
+=
- 字符串可以和int類型相乘薪丁,但不能相加
- 可以比較,單字母按順序比猎醇,如
'abc'<'b'
結(jié)果為True
類型轉(zhuǎn)換:
- 使用int(value)來將value轉(zhuǎn)換為int
變量:
- 變量可以直接使用窥突,不用聲明努溃,并且可以重復(fù)賦值硫嘶。可以使用del 刪除變量
- 命名:
- 單下劃線開頭表示模塊私有梧税,使用import導(dǎo)入時不會包含
- 雙下劃線開頭表示類內(nèi)私有
- 類和異常使用Pascal風(fēng)格(單詞首字母大寫)
- 常量使用全大寫加下劃線
- 其他即使是模塊名也使用全小寫加下劃線
類型:
- Boolean:
True
和False
沦疾,首字母大寫
語句:
- 控制語句后需要加
:
称近,代碼塊使用Tab
縮進進行分割 - 邏輯運算符,和其他語言不一樣了哮塞。
and
or
-
not
取反刨秆,注意Python是有!=
這個比較符的
- 運算符優(yōu)先級問題,請直接加
()
List
- 使用
[,,,,]
形式創(chuàng)建忆畅,數(shù)組沒有固定的類型衡未,元素可以是任何類型 - 字符串可以看作不能改變的字符數(shù)組
- 數(shù)組可以使用
+
、*
- 可以使用
in
來判斷數(shù)組中是否包含否個元素家凯,'a' in 'array'
返回True
- 使用
.append(item)
添加元素 - 使用
len(array)
獲取array
的長度 - 使用
array.insert(index,item)
在array
的指定index
位置插入item
- 使用
array.index(item)
獲取指定元素第一次出現(xiàn)的索引缓醋,未找到則觸發(fā)ValueError
Range,用來創(chuàng)建順序的數(shù)字列表
-
range(10)
绊诲,從0到指定數(shù)字送粱,相當(dāng)與range(0,10,1)
-
range(3,8)
,[3,4,5,6,7]
掂之,從3
開始抗俄,不包含8
-
range(3,8,3)
,[3,6]
,從3
開始世舰,每隔3
個动雹,不包含8
- 使用
list(range)
,可以將range轉(zhuǎn)為數(shù)組
for
-
for item in items:
形式冯乘,items可以是數(shù)組洽胶、range -
switch
,可以將case條目和對應(yīng)的方法構(gòu)建一個字典裆馒,自行實現(xiàn)switch
方法
- 方法的定義是統(tǒng)一的
def fun_name():
姊氓,有返回值也不用聲明,方法體內(nèi)寫return
即可喷好。 - 方法可以被賦值給一個普通變量翔横,比如
a
,之后可以使用a()
調(diào)用 - 方法也可以作為參數(shù)傳遞梗搅。
注釋
- 用
#
- 多行注釋禾唁,沒有,請用多個
#
- 文檔注釋无切,在方法聲明下面使用三引號括住荡短。如下:
def add(x,y): """ 加法。 """ print(x+y)
模塊:
from math import pi,sqrt
import pi from math
import pi from math as PI
標(biāo)準(zhǔn)庫:
- 有用python寫的哆键,有用C寫的掘托。大部分都是跨平臺的,也有Windows和Unix專用的
- PyPI(Python Package Index)存放了各種第三方模塊籍嘹,是用它們最好的辦法是通過pip
異常:
- 類型
- ImportError
- IndexError
- NameError
- SyntaxError
- TypeError
- ValueError
- 捕獲
- try...except...
- try...except(ValueError,TypeError)
- 同樣支持finally
- 拋出異常
raise ValueError('Detail')
- 可以通過
assert (5 >= 0), "Colder than absolute zero!"
進行一次斷言闪盔,如果出錯會拋出AssertionError
try: num = 5 / 0 except: print("An error occurred") raise
文件:
- 打開文件弯院,
file=open(path)
-
open('path')
相當(dāng)于open('path','r')
默認(rèn)只讀 -
open('path','w')
,只寫 -
open('path','a')
泪掀,追加模式 -
open('path','wb')
听绳,在后面加上一個b
意味著以二進制模式打開,常用于圖像和音頻异赫。 -
+
椅挣,r+
可讀可寫;w+
可讀可寫塔拳,沒有就創(chuàng)建贴妻;a+
可讀可寫,沒有就創(chuàng)建蝙斜,指針在文件末尾名惩;同樣可以在后邊加上b
;
-
- 關(guān)閉文件孕荠,
file.close()
娩鹉,在操作系統(tǒng)級別對打開的文件數(shù)目有限制。 - 讀取文件稚伍,
content=file.read()
-
file.read(16)
讀16個字節(jié)的內(nèi)容 - 繼續(xù)調(diào)用
file.read(11)
弯予,會接著之前的繼續(xù)讀 - 如果沒有可讀內(nèi)容后,會返回一個空字符串个曙。
- 可以調(diào)用
file.readlines()
锈嫩,改方法會返回一個字符串?dāng)?shù)組。
-
- 寫入文件垦搬,
file.write('str')
呼寸,如果寫入成功,返回寫入了多少字節(jié)猴贰。- 寫入后需要調(diào)用file.close()对雪,才能保存更改。
- 最佳實踐米绕,使用
with
try: with open("path", "a") as file: file.write('Hello World') except: raise
更多類型:
-
None
瑟捣,類似其他語言的null
。-
bool(None)
返回False
-
print(None)
輸出None
- 沒有返回值的方法返回
None
-
-
Dictionaries
栅干,字典{'key1':value,'key2':value}
- 使用
dict['key']
訪問元素迈套,如果試圖訪問一個不存在的元素,會拋出KeyError
- 只有不可變對象可以用作
key
碱鳞,因為可變對象不可被hash - 方法
- 使用
dict['key']=value
來添加一個鍵值對 - 使用
in
或者not in
判斷一個key
是否存在于字典內(nèi)桑李。 - 使用
get
可以類似索引一樣訪問,只是能夠返回一個默認(rèn)值。print(pairs.get(12345, "not in dictionary"))
- 使用
-
Tuples
芙扎,元組,不可變版本的List填大,使用()
創(chuàng)建戒洼。- 元組本身不可變,但如果他有一個可變的條目比如
list
允华,該list
的內(nèi)容是可變的圈浇。 - 也可以不用
()
,比如my_tuple = "one", "two", "three"
- 元組本身不可變,但如果他有一個可變的條目比如
-
Sets
靴寂,集合- 使用
{1,2,3,4,5}
或set(list)
創(chuàng)建 - 不能使用
{}
創(chuàng)建磷蜀,{}
用于創(chuàng)建字典。創(chuàng)建空的集合可以使用set()
- 可以使用
in
和not in
檢查元素 - 無序的百炬,不能被索引褐隆。
- 不能包含雙重的。
- 比list快
- 不使用
append
使用add
剖踊,remove
移除特定元素庶弃,pop
刪除任意元素。 - 操作符
first = {1, 2, 3, 4, 5, 6} second = {4, 5, 6, 7, 8, 9} print(first | second) print(first & second) print(first - second) print(second - first) print(first ^ second) >>> {1, 2, 3, 4, 5, 6, 7, 8, 9} {4, 5, 6} {1, 2, 3} {8, 9, 7} {1, 2, 3, 7, 8, 9} >>>
- 使用
-
Generators
- 也是
iterable
的一種德澈,不能使用下標(biāo)訪問歇攻,可以使用for循環(huán)遍歷。 - 使用方法和
yield
創(chuàng)建梆造。方法每一次都執(zhí)行到yield
缴守,并返回后跟的值 - 因為它是不斷運行不斷的生成值并返回,所以即使是無限大的序列也是可以的镇辉,不會占用太多內(nèi)存屡穗。
- 有限的
Generators
可以通過list()
轉(zhuǎn)成一個list
def countdown(x): while(x>=0): yield x x-=1 for x in countdown(10): print(x)
- 也是
-
Decorators
- 可以去修改一個方法,類似代理模式忽肛。
def decor(func): def wrap(): print("============") func() print("============") return wrap def decor1(func): def wrap1(): print("**************") func() print("**************") return wrap1 @decor @decor1 def print_text(): print("Hello world!") print_text(); the outcome: =========== ************** Hello world! ************** ===========
-
Recursion
遞歸鸡捐,用于自引用的解決相同類型的更小的子問題。- 需要一個退出條件麻裁。
- 互相調(diào)用也可以稱為遞歸箍镜。
List切片
-
list[3:7]
,返回一個新的list包含原list的第3到第6項煎源,第一個省略色迂,則是從零;第二個省略手销,則是終點歇僧。 - 切片還可以有第三個參數(shù),間隔\步長
- 可以使用負數(shù),當(dāng)前兩個參數(shù)使用負數(shù)時诈悍,表示倒數(shù)第幾個祸轮;當(dāng)?shù)谌齻€參數(shù)使用負數(shù)時,表示反向侥钳。比如适袜,可以使用
list[::-1]
來反轉(zhuǎn)一個list。
List推導(dǎo)
-
cubes = [i**3 for i in range(5)]
返回[0, 1, 8, 27, 64]
- 還可以使用
if
來使值滿足一定的條件舷夺,比如evens=[i**2 for i in range(10) if i**2 % 2 == 0]
- 如果一次創(chuàng)建過大的list會引發(fā)
MemoryError
苦酱,比如even = [2*i for i in range(10**100)]
字符串格式化
- 使用位置參數(shù),
print("{0},{0},{0}".format(1,2,3))
輸出1,1,1
- 也可以使用指定參數(shù)给猾,
print("{x},{0},{y}".format(1,x=1,y=2))
輸出1,1,2
常用的字符串方法:
-
join
疫萤,用一個字符作為分隔符連接一個list里的字符串,", ".join(["spam", "eggs", "ham"])
-
replace
敢伸,替換字符串中的某個字符串扯饶,"Hello ME".replace("ME", "world")
,返回Hello world
-
startswith
池颈,endswith
lower``upper
-
split
帝际,與join
相反
常用的數(shù)學(xué)方法:
-
max
`min` -
abs
絕對值 sum
-
round
四舍五入
常用的數(shù)組方法:
-
all
`any`,判斷 -
enumerate
饶辙,可以用來同時對一個list的索引和值進行迭代
函數(shù)式編程
- 高階方法:把其他的方法作為參數(shù)或者返回值
- 純函數(shù)式:輸入一定蹲诀,輸出一定,不依賴其他狀態(tài)弃揽。復(fù)用性好脯爪,邏輯清楚。
Lambda
- 語法:
lambda arg1,arg2:statement
矿微,lambda
后跟參數(shù)列表痕慢,然后是一個:
,最后是表達式 - 很方便的創(chuàng)建匿名函數(shù)涌矢,也可以將其分配給一個變量掖举。
常用的內(nèi)建高階函數(shù):map
和filter
-
map(func,iterables)
,對iterables
的每一項執(zhí)行func()
操作娜庇。函數(shù)返回值也是一個iterables
塔次,所以我們常用list(result)
將其轉(zhuǎn)化為list -
filter(determine-func,iterables)
,對iterables
的每一項執(zhí)行func()
保留返回True
的項目名秀。返回值同上
itertools
- 一個標(biāo)準(zhǔn)庫包含多種有用的操作
-
count(n)
從n開始產(chǎn)生無限的序列 list(repeat("Huri", 5))
cycle("Huri")
-
takewhile\chain\accumulate
from itertools import accumulate, takewhile nums = list(accumulate(range(8))) print(nums) print(list(takewhile(lambda x: x<= 6, nums))) >>> [0, 1, 3, 6, 10, 15, 21, 28] [0, 1, 3, 6] >>>
-
takewhile
和fliter
的區(qū)別首先是takewhile
只要遇到一個不符合的励负,就直接返回前邊的,不再對后面的進行判斷匕得。 -
chain
的參數(shù)是兩個iterable
-
accumulate
是對每一個都加上(前面所有的和)
-
-
product
andpermutation
from itertools import product, permutations letters = ("A", "B") print(list(product(letters, range(2)))) print(list(permutations(letters))) >>> [('A', 0), ('A', 1), ('B', 0), ('B', 1)] [('A', 'B'), ('B', 'A')] >>>
面向?qū)ο?/h2>
封裝:
class Dog
- 所有方法聲明继榆,第一個參數(shù)都需要指向?qū)嵗牡诙€參數(shù)開始才能指向真實的參數(shù)。包括構(gòu)造器方法略吨。
- 構(gòu)造器:
__init__
集币,只能沒有或有一個〈渲遥可以在里面聲明實例屬性鞠苟。
- 在構(gòu)造方法外聲明的屬性是類屬性,也可以在寫代碼的時候直接寫负间,類名后直接寫一個屬性,就是類屬性姜凄,實例后跟一個屬性就是實例屬性政溃。
- 試圖訪問一個沒有的屬性或方法會引發(fā)異常
AttributeError:
繼承和多態(tài):
class Dog(Animal):
- 如果重寫了父類的方法,則會調(diào)用自己的方法态秧。
- 注意董虱,如果子類和父類方法名一致,但參數(shù)不一致申鱼,即使子類實例調(diào)用該方法的方法參數(shù)和父類一致愤诱,子類實例還是會調(diào)用子類的方法,然后報參數(shù)錯誤捐友。
- 調(diào)用父類的某個方法
super().spam()
魔術(shù)方法
class Dog
__init__
集币,只能沒有或有一個〈渲遥可以在里面聲明實例屬性鞠苟。AttributeError:
class Dog(Animal):
- 注意董虱,如果子類和父類方法名一致,但參數(shù)不一致申鱼,即使子類實例調(diào)用該方法的方法參數(shù)和父類一致愤诱,子類實例還是會調(diào)用子類的方法,然后報參數(shù)錯誤捐友。
super().spam()
是在開頭和結(jié)尾都有雙下劃線的方法淫半。
- 操作符重載
-
def __add__(self, other):
- 如果
a
實現(xiàn)了__add__
,a+b
->a.__add__(b)
- 如果
a
沒實現(xiàn)匣砖,a+b
->b._radd__(a)
- 都沒實現(xiàn)科吭,則
TypeError: unsupported operand type(s) for +:
- 如果
- 計算操作表
__sub__ for - __mul__ for * __truediv__ for / __floordiv__ for // __mod__ for % __pow__ for ** __and__ for & __xor__ for ^ __or__ for |
- 這些方法都和上面的
+
邏輯一樣,也都有對應(yīng)的r
方法
- 這些方法都和上面的
- 對比操作表
__lt__ for < __le__ for <= __eq__ for == __ne__ for != __gt__ for > __ge__ for >=
- 如果
__ne__
沒有實現(xiàn)猴鲫,會執(zhí)行__eq__
并取反返回
- 如果
- 常用魔術(shù)方法
__len__ for len() __getitem__ for indexing __setitem__ for assigning to indexed values __delitem__ for deleting indexed values __iter__ for iteration over objects (e.g., in for loops) __contains__ for in
- 不常用魔術(shù)方法
__call__ 方法調(diào)用 __int__ for int() __str__ for str()
-
生命周期
對象實例的創(chuàng)建对人、操作和銷毀
對象的定義
-
實例初始化,
__init__
被調(diào)用拂共,這時對象內(nèi)存就分配了牺弄。如果有__new__
的話,就不會調(diào)用__init__
-
__new__
是用創(chuàng)建對象的 -
__init__
用來初始化的
-
實例刪除宜狐,
__del__
方法势告,引用計數(shù)-1,分配名字或放置到容器中時引用計數(shù)+1抚恒,當(dāng)引用計數(shù)為0或只有互相引用時培慌,內(nèi)存被釋放。-
類方法使用
@classmethod
修飾class Rectangle: def __init__(self, width, height): self.width = width self.height = height def calculate_area(self): return self.width * self.height @classmethod def new_square(cls, side_length): return cls(side_length, side_length) square = Rectangle.new_square(5) print(square.calculate_area()) >>> 25 >>>
-
靜態(tài)方法柑爸,
staticmethod
修飾吵护,不需要第一個參數(shù)class Pizza: def __init__(self, toppings): self.toppings = toppings @staticmethod def validate_topping(topping): if topping == "pineapple": raise ValueError("No pineapples!") else: return True ingredients = ["cheese", "onions", "spam"] if all(Pizza.validate_topping(i) for i in ingredients): pizza = Pizza(ingredients)
-
屬性,``修飾,常用于使屬性變?yōu)橹蛔x
class Pizza: def __init__(self, toppings): self.toppings = toppings @property def pineapple_allowed(self): return False pizza = Pizza(["cheese", "tomato"]) print(pizza.pineapple_allowed) pizza.pineapple_allowed = True
-
屬性的
setter
和getter
class Pizza: def __init__(self, toppings): self.toppings = toppings self._pineapple_allowed = False @property def pineapple_allowed(self): return self._pineapple_allowed @pineapple_allowed.setter def pineapple_allowed(self, value): if value: password = input("Enter the password: ") if password == "Sw0rdf1sh!": self._pineapple_allowed = value else: raise ValueError("Alert! Intruder!") pizza = Pizza(["cheese", "tomato"]) print(pizza.pineapple_allowed) pizza.pineapple_allowed = True print(pizza.pineapple_allowed) >>> False Enter the password to permit pineapple: Sw0rdf1sh! True >>>
正則
目的
- 驗證字符串是否匹配
- 在一個字符串中進行替換
Python中的使用:
-
re
模塊 - 使用
re.match
匹配馅而,匹配返回表示匹配的對象祥诽,否則返回None - 使用
r
不會轉(zhuǎn)義任何字符串內(nèi)容。
方法
-
re.match
- 從開頭開始匹配
-
re.search
- 從任意地方匹配
-
re.findall
- 返回一個字符串list
-
re.sub(pattern, repl, string, max=0)
替換
正則匹配對象的方法
import re
pattern = r"pam"
match = re.search(pattern, "eggspamsausage")
if match:
print(match.group())
print(match.start())
print(match.end())
print(match.span())
>>>
pam
4
7
(4, 7)
>>>
Groups
-
group(0)
或group()
返回整個匹配對象 -
group(n)
返回從1開始數(shù)瓮恭,按(
出現(xiàn)的位置 -
groups()
返回除了geoup(0)
以外所有的匹配的list
import re
pattern = r"a(bc)(de)(f(g)h)i"
match = re.match(pattern, "abcdefghijklmnop")
if match:
print(match.group())
print(match.group(0))
print(match.group(1))
print(match.group(2))
print(match.groups())
>>>
abcdefghi
abcdefghi
bc
de
('bc', 'de', 'fgh', 'g')
>>>
特殊的group
- 命名
group
雄坪,(?P<name>...)
- 不捕獲
group
,(?:...)
import re
pattern = r"(?P<first>abc)(?:def)(ghi)"
match = re.match(pattern, "abcdefghi")
if match:
print(match.group("first"))
print(match.groups())
>>>
abc
('abc', 'ghi')
>>>
特殊序列:反斜杠和1到99之間的數(shù)字屯蹦,例如\1
或\17
维哈。這匹配該數(shù)字的組的表達式。
import re
pattern = r"(.+) \1"
match = re.match(pattern, "word word")
if match:
print ("Match 1")
match = re.match(pattern, "?! ?!")
if match:
print ("Match 2")
match = re.match(pattern, "abc cde")
if match:
print ("Match 3")
>>>
Match 1
Match 2
>>>
正則元字符
-
.
登澜,除了新行之外的所有字符 -
^
和$
,匹配開始和結(jié)尾 -
[]
匹配方括號中的一個 -
[a-z]
阔挠,-
表示范圍 -
[^a-z]
,^
表示非 -
*``+``?``{}
脑蠕,?
相當(dāng)于{0,1}
-
\d
匹配數(shù)字购撼,\s
匹配空格,\w
字符()谴仙,大寫表示相反 -
\b
字符邊界
其他內(nèi)容
Python之禪
使用import this
運行迂求,控制臺會輸出下面的內(nèi)容
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
Python之禪有20條原則,這里面只提到了19條晃跺,第二十條是使用空白 :)
PEP
Python Enhancement Proposals (PEP)是經(jīng)驗豐富的Python開發(fā)者的建議揩局,PEP8作為一個風(fēng)格指南有很多條規(guī)則。
除了本文一開始的命名規(guī)范掀虎,主要還有這些內(nèi)容:
- 一行不應(yīng)該超過80個字符
- 不要使用
from module import *
- 每行只應(yīng)該有一條語句
方法參數(shù)
- 可變參數(shù)
*args
谐腰,方法內(nèi)使用元組訪問,必須在命名參數(shù)之后涩盾,args
不是規(guī)定的名字十气。def function(named_arg, *args): print(named_arg) print(args) function(1, 2, 3, 4, 5) >>> 1 (2, 3, 4, 5) >>>
- 默認(rèn)參數(shù)。命名參數(shù)可以有一個默認(rèn)值春霍,必須在沒有默認(rèn)值的命名參數(shù)之后
def function(x, y, food="spam"): print(food) function(1, 2) function(3, 4, "egg") >>> spam egg >>>
- 關(guān)鍵詞參數(shù)砸西,
**kwargs
可以用于處理你沒有定義的命名參數(shù),以字典的形式傳入址儒。放在最后面def my_func(x, y=7, *args, **kwargs): print(kwargs) my_func(2, 3, 4, 5, 6, a=7, b=8) >>> {'a': 7, 'b': 8} >>>
元組解包
將一個iterable
(通常是Tuple
)的每一項賦值給一個變量芹枷,以*
開頭的變量會取出其他剩余的值,保證成一個list
a, b, *c, d = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(a)
print(b)
print(c)
print(d)
>>>
1
2
[3, 4, 5, 6, 7, 8]
9
>>>
三元運算符 b = (value) if (statement) else (another-value)
else
else可以配合for使用莲趣,當(dāng)for循環(huán)正常結(jié)束時會調(diào)用else的語句鸳慈,如果break則不會調(diào)用該語句。
for i in range(10):
if i == 999:
break
else:
print("Unbroken 1")
for i in range(10):
if i == 5:
break
else:
print("Unbroken 2")
>>>
Unbroken 1
>>>
else也可以配合try...except...使用喧伞,只有在try正常執(zhí)行完畢時才會調(diào)用else
try:
print(1)
except ZeroDivisionError:
print(2)
else:
print(3)
try:
print(1/0)
except ZeroDivisionError:
print(4)
else:
print(5)
>>>
1
3
4
>>>
__main__
被當(dāng)作模塊導(dǎo)入時走芋,名字不會是__main__
绩郎。如果Python解釋器正在將該模塊(源文件)作為主程序運行,則會將特殊的__name__
變量設(shè)置為__main__
翁逞。如果這個文件是從另一個模塊導(dǎo)入的肋杖,__name__
將被設(shè)置為模塊的名字。
def function():
print("This is a module function")
if __name__=="__main__":
print("This is a script")
>>>
This is a script
>>>
主要的三方庫
- 流行的Web框架挖函,
Django
(Instagram和Disqus都在使用)状植、CherryPy和Flask
- 抓包,
BeautifulSoup
-
matplotlib
允許你創(chuàng)建基于Python數(shù)據(jù)的圖表 -
NumPy
怨喘,極快的多維數(shù)組和數(shù)學(xué)運算津畸。 -
SciPy
包含許多對NumPy
的擴展 - 用于3D游戲的
Panda3D
,用于2D游戲的pygame
打包
將模塊寫成標(biāo)準(zhǔn)格式必怜,使其他程序員可以輕松安裝和使用它們肉拓。需要用到setuptools
和distutils
兩個模塊
- 第一步是正確組織現(xiàn)有文件,將所有要放入庫的文件放在同一個父目錄中棚赔。該目錄還應(yīng)該包含一個名為
__init__.py
的文件帝簇,該文件可以是空白的徘郭,但必須存在于目錄中靠益。 - 把這個目錄放到另一個包含自述文件和許可證的目錄,以及一個名為setup.py的重要文件残揉。最后的結(jié)構(gòu)如下:
SoloLearn/ LICENSE.txt README.txt setup.py sololearn/ __init__.py sololearn.py sololearn2.py
- 寫
setup.py
胧后,包含必要的信息,如名字抱环、版本等from distutils.core import setup setup( name='SoloLearn', version='0.1dev', packages=['sololearn',], license='MIT', long_description=open('README.txt').read(), )
- 上傳到
PyPI
壳快,分為源代碼發(fā)行版和二進制發(fā)行版。 - 在目錄里可以使用
python setup.py install
安裝
打包成可執(zhí)行文件
考慮有些普通用戶沒有裝Python镇草,所以直接打包成對應(yīng)平臺的可執(zhí)行文件眶痰。
- Windows
py2exe
PyInstaller
cx_Freeze
- Mac
py2app
PyInstaller
cx_Freeze