python的單例模式
class A(object):
__instance = None
def __new__(cls):
if not cls.__instance:
cls.__instance = object.__new__(cls)
return cls.__instance
return cls.__instance
python的繼承
- python的子類會繼承父類公開的方法和魔法方法
- 類屬性是屬于類的, 是以公開的也會被繼承
- 類屬性隻能被類修改和删除
- 在__init__方法中調用super().__init__(父類的參數清單)
- 定義接口的話, 則在父類方法的實作使用pass關鍵字
python的異常處理
try:
except Exception as ex:
finally:
- 抛出異常
- raise MyException('Error')
python的屬性命名
python的類方法與靜态方法
@classmethod
# test的第一個形參必須為cls
def test(cls):
@staticmethod
# 不會傳遞預設的cls參數
def test():
初始化屬性
繼承基類的查找
搜尋區域
- locals -> globals -> builtins
在函數中修改全局變量
- globals globl_val
- globl_val = 10
通路一個對象的屬性
- 會通過__getattribute__魔法方法, 一不小心就是讓挂了
閉包
pdb使用
- python -m pdb file.py
- c, b, n, r, p
類修飾器
class Test(object):
def __init__(self, func):
print('Test init')
self.__func = func
def __callable__(self):
print('Call...')
self.__func()
@Test # 會将func作為傳入到Test(func)中
def func():
print('This is func function')
del語句的實質
- del用來較少對象的引用, 與C++中的delete不同, delete是将指針指向的對象的記憶體空間釋放掉
程序
- import os
- os.fork() 底層調用的是C中庫函數fork()
- 使用mutilprocessing.Process類的start()方法進行初始化
- 繼承Process類, 重寫run方法
- 使用程序池
- Pool(size)
- pool.apply_async(func, args=(), kwargs={}) # 程序不等待
- pool.apply() # 程序會阻塞
- pool.close() # 關閉pool, 讓pool不在接受請求
- pool.terminate() # 終止任務
- pool.join() # 等待子程序
線程
- import threading
- 調用th = threading.Thread(target=work, args=(), kwargs={})
- th.start()
- threading.current_thread().name
- threading.current_thread().getName(), isAlive(), setName()
- th.join()
- th.terminate()
- 采用繼承的方式實作線程
- 繼承threading.Thread, 重載run方法
線程鎖
- mutex = threading.Lock()
- mutex.acquire()
- mutex.release()
線程隊列
- import queue
- queue.Queue中的元素存取的時候都是線程安全的, 是以一般線程安全的擷取資源就是使用Queue
- q.put(), q.get()
- 該queue是自定義線程池的基礎, 首先一個while中不斷get程序start, 後面在加上thread
套接字程式設計(socket就是API)
- 類: socket.socket()
- 方法: s.sendto(), s.recvfrom()
注意點
- fork出來的程序有自己獨立的記憶體空間, 與線程是不同的