Python中單例設計模式

來源:互聯網
上載者:User

標籤:not   個人   設計   self   列印   構造   pos   單例設計   import   

import os# 單例設計模式,只返回一個對象class Singlet(object):    _instance=None    _first_init=False    # 類一建立就初始化(個人理解:類似java中的構造方法),必須有傳回值    def __new__(cls,age,name):        if not cls._instance:            cls._instance=object.__new__(cls)        return cls._instance    # 初始化資料    def __init__(self,age,name):        if not self._first_init:            self.age=age            self.name=name            Singlet._first_init=True    # 定義統一列印的方法    def __str__(self):        return "姓名為:%s"%self.name+"  年齡為:%d"%self.age    # 對象再被銷毀之前,調用此方法,可以做一些資源的釋放,流的關閉等    def __del__(self):        print("我被刪除了")# 以下雖然建立兩個對象,# 但是他們是通過單例的設計模式,只建立了一個對象,# 所以,結果值是一樣的a=Singlet(26,"xiaokeke")b=Singlet(22,"liulili")print(id(a))print(id(b))print(a.name)print(b.name)# 結果如下:#2585443917896#2585443917896# xiaokeke# xiaokeke# 我被刪除了

  

Python中單例設計模式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.