聲明文件字符集
# -*- coding: cp-1252 -*-
數(shù)的表示方法
100 # 十進(jìn)制
0xff00 # 16進(jìn)制
1.23 # 浮點(diǎn)數(shù)
1.23e10 # 浮點(diǎn)數(shù)科學(xué)計(jì)數(shù)法
數(shù)學(xué)計(jì)算
加減乘除取余與其他語(yǔ)言相同
17//3 #不要余數(shù)的除法
5**2 #冪運(yùn)算
2 & 3 #二進(jìn)制按位與
2 | 3 #二進(jìn)制按位或
2 ^ 3 #二進(jìn)制按位異或
2 ~ 3 #二進(jìn)制按位取反
1 << 10 #二進(jìn)制左移——1024
1024 >> 2 #二進(jìn)制右移——256
邏輯運(yùn)算采用and
or
not
表示
成員運(yùn)算in
not in
身份運(yùn)算(判斷引用)is
is not
運(yùn)算優(yōu)先級(jí):
**
~ +@ -@
* / % //
+ -
>> <<
&
^ |
<= < > >=
== !=
= %= /= //= -= += *= **=
is is not
in not in
not or and
數(shù)學(xué)函數(shù)(import math
)
abs(x) #絕對(duì)值
ceil(x) #向上取整
floor(x) #向下取整
cmp(x, y) #比較睡毒,返回-1,0,1
exp(x) #e的n次冪
fabs(x) #數(shù)值絕對(duì)值
log(x) #對(duì)數(shù)
log10(x) #含基數(shù)對(duì)數(shù)
max(x1, x2,...) #最大值
min(x1, x2,...) #最小值
modf(x) 分別返回整數(shù)部分和小數(shù)部分
pow(x, y) 冪運(yùn)算
round(x [,n]) 四舍五入
sqrt(x) 平方根
三角函數(shù):acos(x)
asin(x)
atan(x)
atan2(y, x)
cos(x)
hypot(x, y) # 歐幾里得范數(shù)
sin(x)
tan(x)
degrees(x) #弧度轉(zhuǎn)角度
radians(x) #角度轉(zhuǎn)弧度
常量:pi
e
隨機(jī)函數(shù):
choice(seq) #隨機(jī)選取
randrange ([start,] stop [,step]) #指定范圍隨機(jī)數(shù)
random() #0-1隨機(jī)數(shù)
seed([x]) #自定義生成器
shuffle(lst) #序列隨機(jī)排列
uniform(x, y) #隨機(jī)x-y實(shí)數(shù)
條件&循環(huán)
python的else if寫作elif
python不支持switch
while x>0:
for x in range(10):
break中斷整個(gè)循環(huán)
continue跳過(guò)當(dāng)前循環(huán)
pass僅僅用于占位
字符串
單雙引號(hào)可互相嵌套
*
可以重復(fù)輸出字符串串
r
無(wú)轉(zhuǎn)移字符串
ord(str)
chr(num)
字符整數(shù)相互轉(zhuǎn)化
b'adad'
bytes類型數(shù)據(jù)
decode('utf-8',errors='ignore')
解碼相應(yīng)字符串
可以通過(guò)數(shù)組方法索引拙绊,可以切片塘匣,可以使用成員運(yùn)算符
格式化字符串: %d #十進(jìn)制
%f #浮點(diǎn)數(shù)
%s #字符串
%x #十六進(jìn)制
%o #八進(jìn)制
'%d%s'%(10,'test') #%格式化
'{0:d}{1:s}'.format(10,'test') #format格式化
'''
這是大段字符串
'''
test = 'just a test'
f'{test}'
# 模板字符串
from string import Template
Template('${test}').substitute(test='just a test')
# 模板字符串聲明再實(shí)例
可迭代對(duì)象
列表類似其他語(yǔ)言數(shù)組铛只,表現(xiàn)形式相同煌集,可以不同類型元素
元組是小括號(hào)列表
字典類似對(duì)象叁扫,但是鍵可以是所有不可變對(duì)象地来,包括元組乘寒,字典沒(méi)有順序
集合是不重復(fù)的列表
#用已有可迭代對(duì)象構(gòu)建迭代器
test_1 = iter([1,2,3])
#自定義可迭代對(duì)象
def __iter__(self):
return self
所有可迭代對(duì)象除了元組都是可變對(duì)象
函數(shù)
#匿名函數(shù)
def test(cb):
print(cb(2))
test(lambda x:x)
#裝飾器——任何返回函數(shù)的高階函數(shù)
def test(dec_data):
def wrapper(function):
def dec(*args, **kw): # 原函數(shù)會(huì)被替換
print(args, kw)
print(dec_data)
return function(*args, **kw)
return dec
return wrapper
@test('shit')
def test2(a, b, *args, **kw): # 非關(guān)鍵字參數(shù) 關(guān)鍵字參數(shù)——被解析為dict
print('just a test')
test2(1, 2, 3, 4,test = 3)
print(test2.__name__)
#偏函數(shù)——固定參數(shù)
from functools import partial
def test(a, b):
if b < 5:
print('b<5')
if a < 5:
print('a<5')
test2 = partial(test,a=1,b=6)
test2()
異步相關(guān)
# 生成器在有值的時(shí)候返回
import time
def test_1():
time.sleep(1) # 一般用while
yield print('success')
test_1_runner = test_1()
next(test_1_runner)
# coroutine 協(xié)程
import time
import types
import asyncio
@types.coroutine
def test_2():
time.sleep(1)
yield print('success')
async def test_3():
await test_2()
asyncio.get_event_loop().run_until_complete(asyncio.wait([test_3()]))
# 協(xié)程在事件循環(huán)中執(zhí)行
test_3().send(None)
# 協(xié)程直接執(zhí)行
類相關(guān)
__
表示不能被外部訪問(wèn)(私有)
__init__
構(gòu)造函數(shù)
(self)
所有成員函數(shù)的self參數(shù)表示自引用
class Student(object):
表示繼承
# 繼承
class Test_1:
name = 'name'
class Test_2(Test_1):
def __init__(self):
print(self.name)
Test_2()
# 組合依賴注入
class Test_1:
name = 'name'
class Test_2:
def __init__(self, com):
print(com().name)
Test_2(Test_1)
# 限制屬性
class Test(object):
__slots__ = ('name')
test = Test()
test.name = 1
test.func = 2
# getter setter
class Test(object):
@property
def test_1(self):
return self.__test_1
@test_1.setter
def test_1(self,val):
self.__test_1 = val
__str__()
自定義打印顯示
__repr__()
交互解釋器中的顯示
__getitem__()
數(shù)組方法訪問(wèn)
__getattr__()
對(duì)象方法訪問(wèn)
__call__
函數(shù)方法
# 枚舉類
from enum import Enum
Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')) # 類工廠寫法
# 限制不重復(fù)
from enum import Enum, unique
@unique
class Weekday(Enum):
Sun = 0 # Sun的value被設(shè)定為0
Mon = 1
Tue = 2
Wed = 3
Thu = 4
Fri = 5
Sat = 6
# 類工廠 傳入類名的诵,父類元組万栅,屬性字典
Hello = type('Hello', (object,), dict(hello=fn))
# 元類 繼承type,重載__new__方法
class Test1(type):
def __new__(cls, name, bases, attrs): # 第一個(gè)參數(shù)是當(dāng)前實(shí)例
attrs['name'] = lambda self, value: print(value)
return type.__new__(cls, name, bases, attrs)
class Test2(metaclass=Test1):
pass
錯(cuò)誤
try拋出西疤,except處理烦粒,finally執(zhí)行完畢
凡是用print可以打印的地方,都可以用assert斷言替代
def foo(s):
n = int(s)
assert n != 0, 'n is zero!'
return 10 / n
logging可以輸出到文件代赁,并不會(huì)拋出錯(cuò)誤
pdb.set_trace()設(shè)置斷點(diǎn)