1. 程式人生 > >Python 3.6 單例模式 __new__實現

Python 3.6 單例模式 __new__實現

# -----------------------
# __Author : tyran
# __Date : 17-11-14
# -----------------------
class Base:
    __instance = None
    def __init__(self, num):
        self.num = num

    def show(self):
        print(self.num)

    def __new__(cls, *args, **kwargs):
        if cls.__instance is None:
            cls
.__instance = super().__new__(cls) return cls.__instance b1 = Base(2) b1.show() b2 = Base(3) b1.show() b2.show()