1 基礎
基本數(shù)據(jù)類型:
int
float
str
bool
,類型轉換:int()
float()
str()
+
-
*
/
//
%
**
0b
0B
二進制;0o
0O
八進制;0x
0X
十進制切片:
[start : end : step]
list
tuple
dict
set
,list()
tuple()
dict()
set()
[x for x in range(1,9) if x%2 == 0]
-
''' long long string can change line'''
除了用于文本,還有package和function的文檔說明。
if condiction: ... elif condiction: ... else: ...
while condiction: ... else: ...
for condiction: ... else: ...
2 模塊與包
-
導入模塊或包
import packagename import packagename as pn from random import choice
-
模板
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ' a test module ' __author__ = 'Michael Liao' import sys def test(): args = sys.argv if len(args)==1: print('Hello, world!') elif len(args)==2: print('Hello, %s!' % args[1]) else: print('Too many arguments!') if __name__=='__main__': test()
3 函數(shù)
-
help() type() repr() len() sorted() dir() encode() decode() format() map(function, iter) #對iter中的每個元素執(zhí)行function操作 reduce(function, iter) #等價于 result = function(iter[0], iter[1]) result = function(result, iter[2]) ... result = function(result, iter[-1]) filter(function, iter)
-
自定義函數(shù)
#function of python def function(*args) #調用時對應的參數(shù)打包成一個名為args的list送入函數(shù) def function(**kwargs) #調用時對應的參數(shù)打包成一個名為kwargs的dict送入函數(shù) def function(): 'this is a function doc' pass def function(): ''' this is a function doc's first line; this is a function doc's second line.''' pass print(function.__doc__) #輸出函數(shù)的文檔 print(function.__name__) #輸出函數(shù)的名字 def func_a(): pass def func_b(func_a): #函數(shù)是一級公民 func_a() def outer(): def inner(): #函數(shù)內部定義函數(shù) pass #閉包 用一個函數(shù)定義生成一組類似的函數(shù) def write_log(error_type): def print_log(): return 'error type is: ' + error_type return print_log a = write_log('disk error') b = write_log('memory error') #a,b是不同的函數(shù) #匿名函數(shù) def print_result(result, function): for number in result: print(function(number)) #example result = [1,2,3,4,5] print_result(result, lambda number: number ** 5) #生成器 def my_range(start, end, step): number = first while number < end: yield number number += step a = my_range(1,5,1) #a的類型是生成器,和range()返回的結果類似 #修飾器 def document_it(func): def new_function(*args, **kwargs): print('Running function:', func.__name__) print('Positional arguments:', args) print('Keyword arguments:', kwargs) result = func(*args, **kwargs) print('Result:', result) return result return new_function @document_it def add_int(a, b): return a+b #等價于 add_int = document_it(lambda a,b: a+b)
4 對象
#class of python
class Car():
def __init__(self, color): #初始化
self.color = color
class Yugo(Car): #繼承
pass
#繼承可以得到父類的方法,但是也可以重寫此方法進行重載
#在子類的定義中,super()是指父類,以此使用父類中的定義
#在定義某個以父類作為參數(shù)的函數(shù)之后,其對子類使用這個函數(shù)(由于多態(tài))
#直接定義的屬性不夠安全,沒有進行檢查
class Car():
def __init__(self, value):
self.color = value
@property #通過property修飾,定義訪問car.color時的行為
def color(self):
return 'the color is: ' + self._color
@color.setter #通過setter修飾,定義對car.color賦值時的行為
def color(self,value):
self._color = value
class Car():
def __init__(self, value):
self.__color = value #__color是無法直接訪問的
class Car():
n = 0
def __init__(self):
n += 1
@classmethod #使用classmethod修飾,定義一個類方法
def counter(cls): #這里的例子是一個計數(shù)器,記錄用Car生成了多少實例
return cls.n
#定義類的特殊方法
#__eq__, __ne__, __lt__, __gt__, __le__, __ge__
#__add__, __sub__, __mul__, __truediv__, __floordiv__, __mod__, __pow__
#__str__, __len__, __repr__
#__iter__, __next__ 用于for ... in ...循環(huán)時的行為
#__getitem__, 用于切片時的行為
#__call__, 用于定義調用該實例時的行為
5 文件
fileobj = open('path/filename', 'mode')
#mode為兩個字符,前一個為rwxa中的一個,為只讀、寫入、新建文件并寫入、在結尾增添;后一個為bt中的一個,表示二進制文件和文本文件
fileobj.close()
with open('path/filename', 'mode') as f: #無需進行f.close()
f.dosomething
fileobj.write(things)
print(things, file = fileobj)
text = fileobj.read(position) #讀取position之后的所有內容
text = fileobj.readline() #讀取一行
position = fileobj.tell() #獲取文件指針的位置
fileobj.seek(offset, origin) #設置文件指針到origin之后offset處
6 異常與錯誤
try:
pass
except ErrorType as a:
print('there is a ',a)
finally:
pass
#拋出錯誤
raise ErrorType(text)
#斷言,用于調試
assert n!=0, 'n is zero' #如果為假,則輸出后面的文本