Python Singleton模式

注意:在重写__new__方法时,object.__new__(cls)不能传参数

#!/usr/bin/env python
# -*- coding: utf-8 -*-

class Singleton():
    __instance = False
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __new__(cls, *args, **kwargs):
        if not Singleton.__instance:
            Singleton.__instance = object.__new__(cls)  #此处不能添加参数
        return Singleton.__instance

s = Singleton('hello', 18)

 

- [Python中的单例模式的几种实现方式的及优化](https://www.cnblogs.com/huchong/p/8244279.html)

posted @ 2018-11-21 18:47  zkeeper  阅读(103)  评论(0编辑  收藏  举报