Python 单例 new的三种方式

python的new方法相当于java的构造方法

class Farther(object):
    def __init__(self):
        print("farther init ")

    def say(self):
        print("farther say")


class Singleton(Farther):

    def __new__(cls, *args, **kwargs):
        if not hasattr(Singleton, "_instance"):
            # Singleton._instance = object.__new__(cls)

            # Singleton._instances = super(
            #     Singleton, cls).__call__(
            #     *args, **kwargs)

            Singleton._instance = super(
                Singleton, cls).__new__(
                cls, *args, **kwargs)
        # result = cls is Singleton
        # print(result) # True

        return Singleton._instance

    def __init__(self):
        super(Singleton, self).__init__()
        print("son init===")


s1 = Singleton()
s2 = Singleton()
print s1, '==='
print s2, '==='

s2.say(), '==='
"""
farther init 
son init===
farther init 
son init===
<__main__.Singleton object at 0x000000000755C7B8> ===
<__main__.Singleton object at 0x000000000755C7B8> ===
farther say
"""

你可能感兴趣的:(python)