基礎(chǔ)語(yǔ)法
- 變量定義:
test = 1
test2 = 'abc'
- 區(qū)塊 使用 :與縮進(jìn)對(duì)齊來(lái)標(biāo)示一個(gè)區(qū)塊, 如其他語(yǔ)言中大括號(hào)中內(nèi)容
if True:
a = 1
b = 2
...
- 函數(shù)定義
def fun(a, b, c = 1, d = 'a'):
print(a, b, c)
# 可變參數(shù)與缺省參數(shù)可以同時(shí)使用
def fun2(*nums, end='\n'):
for n in nums:
print(n)
print(end)
- 控制結(jié)構(gòu)
if cond1 or cond2 and cond3 and not cond4:
pass
elif condition:
pass
else:
pass
# 列表或者迭代器
for i in range(5):
print(i);
a = 5;
while a > 0:
print(a)
a = a - 1
- 容器
# 列表
l = [1, 2, 'a', 'abc']
l.append('end')
l.remove('a')
l.pop(3)
# tuple 不可更改 但是可以更改內(nèi)部的list元素
t = (1,) # 單個(gè)元素必須后續(xù)逗號(hào),否則就不是tuple了
t = ('a', 1, [1, 2])
# dict
d = {'a':1, 'b':2, 'c':[1,2,3]}
d.get('d', -1) # 無(wú)值時(shí)返回提供的默認(rèn)值
# set 支持并集 交集
s = set([1,2,3]) # 使用列表來(lái)初始化
s1 = set([3,4])
print(s & s1) # (3,)
print(s | s1) # (1,2,3,4)
# 容器的切片功能
l[0:3] 或 l[:3] 獲取前三項(xiàng)
l[3:] # 獲取第三到最后一項(xiàng)
l[-3:] # 最后三項(xiàng)
l[::-1] # 倒序
L[:10:2] # 前10個(gè)每?jī)蓚€(gè)選一個(gè)
- 關(guān)鍵字
import keyword
print(keyword.kwlist)
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class',
'continue', 'def', 'del', 'elif', 'else', 'except', 'finally',
'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda',
'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try',
'while', 'with', 'yield']
- 讀寫文件
import os
f = open(filepath, 'r')
f = open(filepath, 'r', encoding='gbk', errors='ignore')
f.read() # 全部讀取
f.read(size) # 讀取指定大小
f.readlines() # 讀取所有并每一行放在列表中
f.write("something")
f.close()
# 使用with 則不用手動(dòng)調(diào)用close 保證關(guān)閉
with open(filepath, 'w') as f:
pass
# path 相關(guān)
os.path.join('/Users/michael', 'testdir') # 鏈接路徑 返回字符串
os.path.split('/Users/michael/testdir/file.txt') # 分拆路徑最后的文件名 或 最后的路徑,返回tuple
os.path.splitext('/path/to/file.txt') # 分拆擴(kuò)展名 返回tuple
# 當(dāng)前目錄下所有的文件夾
[x for x in os.listdir('.') if os.path.isdir(x)]
- 面向?qū)ο?/li>
class TestClass(object): # 繼承 object 也可以繼承其他類
__slots__ = ('name', 'age') # 特殊變量 __slots__可以限制可能存在的成員
static_name = 'TestClass' # 相當(dāng)于靜態(tài)變量 可以通過(guò)class直接訪問(wèn)
# __init__相當(dāng)于構(gòu)造函數(shù)
# 所有函數(shù)的第一個(gè)參數(shù)都要是self 除非不需要對(duì)象的‘靜態(tài)函數(shù)’?
def __init__(self, name):
self.name = name # 這里定義self的各個(gè)字段
self.load(name) # 調(diào)用函數(shù)使用self調(diào)用
def load(self, name):
pass
# 以__開(kāi)頭的函數(shù)或成員為private 實(shí)際上是被重命名了,加了 _TestClass前綴
def __private_fun(self):
pass