python中用裝飾器實現單例模式
阿新 • • 發佈:2018-12-14
def singleton(cls,*args,**kwargs): instances = {} def get_instance(*args,**kwargs): if cls not in instances: instances[cls]= cls(*args,**kwargs) return instances[cls] return get_instance @singleton class Student: def __init__(self,name,age): self.name = name self.age =age sdutent =Student('jiang',25) student2 = Student('zhangsan',26) print(student2.age)
#執行結果
F:\7-9練習程式碼\fuxi\venv\Scripts\python.exe F:/7-9練習程式碼/fuxi/shujujiegou.py
25
Process finished with exit code 0
在Python中認為“一切皆物件”,類(元類除外)、函式都可以看作是物件,既然是物件就可以作為引數在函式中傳遞,我們現在來呼叫Student類來建立例項,看看實現過程。
#建立student例項
student = Student(jiang, 25)
@singleton相當於Student = singleton(Student),在建立例項物件時會先將 Student 作為引數傳入到 singleton 函式中,函式在執行過程中不會執行 get_instance 函式(函式只有呼叫才會執行),直接返回get_instance函式名。
此時可以看作Student = get_instance,建立例項時相當於student = get_instance(jiang, 25),呼叫get_instance 函式,先判斷例項是否在字典中,如果在直接從字典中獲取並返回,如果不在執行 instances [cls] = Student(jiang, 25),然後返回該例項物件並賦值非student變數,即student = instances[cls]。