Python Tips(持續更新)

Python Tips(持續更新)

  • 直接運行py文件,在Mac和Linux上是能夠的,方法是在.py文件的第一行加上一個特殊的註釋: 
1 #!/usr/bin/env python3
2 
3 print('hello, world')

而後,經過命令給hello.py以執行權限:html

$ chmod a+x hello.pypython

 

  • 爲Sublime text2設置Python運行版本
1 {
2   "cmd": ["/usr/local/bin/python3.5", "-u", "$file"],
3   "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
4   "selector": "source.python"
5 }

 

  • 爲Sublime text2的插件SublimeREPL設置Python運行版本
在這個文件:/Users/JackMa/Library/Application Support/Sublime Text 2/Packages/SublimeREPL/config/Python/Main.sublime-menu內進行設置:
 1 {
 2   "command": "repl_open",
 3   "caption": "Python",
 4   "id": "repl_python",
 5   "mnemonic": "P",
 6   "args": {
 7     "type": "subprocess",
 8     "encoding": "utf8",
 9     //"cmd": ["python", "-i", "-u"],原來是這個
10     "cmd": ["/usr/local/bin/python3.5", "-i", "-u"],
11     "cwd": "$file_path",
12     "syntax": "Packages/Python/Python.tmLanguage",
13     "external_id": "python",
14     "extend_env": {"PYTHONIOENCODING": "utf-8"}
15     }
16 }

這裏只對Python這個選項進行了cmd設置,能夠依次在下方的全部children都設置成Python3.5版本數據庫

 

  • 關於設置pip的一些問題
修改pip默認安裝路徑命令:

pip install --install-option="--prefix=/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages" lxmljson

 

  • 使用Mac自帶的iconv命令行工具進行格式轉換

iconv -t utf-8 index.html > index_.html多線程

 

  • str和bytes互相轉換時,須要指定編碼
eg. >>> ‘中文’.encode(‘gb2312’)
      '\xd6\xd0\xce\xc4'
 
  • Python的函數參數形態十分靈活,須要注意的幾點

默認參數必定要用不可變對象,若是是可變對象,程序運行時會有邏輯錯誤!函數

要注意定義可變參數和關鍵字參數的語法:工具

*args是可變參數,args接收的是一個tuple;ui

**kw是關鍵字參數,kw接收的是一個dict。編碼

 

  • Python的切片特性
對某個list、tuple、string可使用 [::] 這種語法進行切片,最後一個數字表示間隔多少取數據
1 L = list(range(100))
2 print(L[0:10])
3 print(L[-10:])
4 L = 'asdfgh'
5 print(L[::2])

 

  • 凡是可做用於for循環的對象都是Iterable類型;

凡是可做用於next()函數的對象都是Iterator類型,它們表示一個惰性計算的序列;spa

Itera​ble經過iter()函數轉換成Iterator

 

 

  • 關於」__xxxx__」的一些經常使用名詞解釋

 

__init__:用於類新建實例時調用

 

__getattr__:當調用實例中不存在的屬性時,Python解釋器會調用此方法

 

__setattr__:

 

__str__:打印類的實例時調用

 

__repr__:調試時打印實例,通常都使__repr__=__str__

 

__call__:調用實例自己時,調用此方法

 

__iter__:使這個類的實例可以用於for...in循環

 

__next__:在做爲發生器時候,用於拿到循環下一個值

 

__getitem__:使這個類實例能夠像list那樣按照下標取值

 

 

 

注:在實現類中使用@property@xxx.setter能夠方便地設置get方法與set方法

 

1 class Screen(object):
2   @property
3   def width(self):
4     return self._width
5 
6   @width.setter
7   def width(self, value):
8     self._width = value

 

 

  • 關於序列化
導入pickle​或者json實現序列化與反序列化
 1 import pickle
 2 d = dict(name='Bob', age=20, score=88)
 3 f = open('/Users/JackMa/Desktop/Python/test3.py', 'wb')
 4 pickle.dump(d, f) #序列化
 5 f.close()
 6 
 7 f = open('/Users/JackMa/Desktop/Python/test3.py', 'rb')
 8 m = pickle.load(f)  #反序列化
 9 print(m)
10 f.close()

 

 1 import json
 2 
 3 print(json.dumps(d))
 4 json_str = '{"age": 20, "score": 88, "name": "Bob"}'
 5 print(json.loads(json_str))
 6 
 7 class Student(object):
 8   def __init__(self, name, age, score):
 9     self.name = name
10     self.age = age
11     self.score = score
12 
13 #對類的序列化用到下面的方法
14 def student2dict(std):
15   return {
16     'name': std.name,
17     'age': std.age,
18     'score': std.score
19   }
20 
21 #對類的反序列化用到下面的方法
22 def dict2student(d):
23   return Student(d['name'], d['age'], d['score'])
24 
25 s = Student('Bob', 20, 88)
26 #下面兩種方法均可以序列化
27 print(json.dumps(s, default=student2dict))  
28 print(json.dumps(s, default=lambda obj:obj.__dict__))
29 json_str = '{"age": 20, "score": 88, "name": "Bob"}'
30 print(json.loads(json_str, object_hook = dict2student)

 

 

  • 關於多線程

頭文件導入threading

建立新線程:t = threading.Thread()

線程開始:t.start()

等待線程執行完畢:t.join()

獲取當前線程:threading.current_thread()

創建線程鎖:lock = threading.Lock()

得到線程鎖:lock.acquire()

釋放線程鎖:lock.release()

建立線程內的全局ThreadLocal對象:local = threading.local() ThreadLocal最經常使用的地方就是爲每一個線程綁定一個數據庫鏈接,HTTP請求,用戶身份信息等,這樣一個線程的全部調用到的處理函數均可以很是方便地訪問這些資源。

 

 1 import time, threading
 2 
 3 local = threading.local()
 4 
 5 def process_student():
 6   std = local.age
 7   print('%s in %s' % (std, threading.current_thread().name))
 8 
 9 def process_thread(temp):
10   local.age = temp
11   process_student()
12 
13 t1 = threading.Thread(target=process_thread, args=(12, ))
14 t2 = threading.Thread(target=process_thread, args=(123, ))
15 t1.start()
16 t2.start()
相關文章
相關標籤/搜索