Skip to content

Python_Sigleton

zjy edited this page Jul 13, 2016 · 1 revision

#Singleton

class method | instance method

Difference between @staticmethod and @classmethod in Python

class class 是每个类实例的一个内置属性 (也是每个类的)。它是一个类的引用,而 self 是一个类 (在本例中,是 counter 类) 的实例。

新式类 旧式类

class A:
    pass

a = A()
print(type(A))
# print(A.__class__) AttributeError: class A has no attribute '__class__'
print(a.__class__)
print(type(a))
# <type 'classobj'>
# __main__.A
# <type 'instance'>
print(a)
# <__main__.A instance at 0x00000000024A2B08>

class B(object):
    pass

b = B()
print(type(B))
print(B.__class__)
print(b.__class__)
print(type(b))
# <type 'type'>
# <type 'type'>
# <class '__main__.B'>
# <class '__main__.B'>
print(b)
# <__main__.B object at 0x0000000001D349E8>

__metaclass__

What is a metaclass in Python?

深刻理解Python中的元类(metaclass)

__new__ __init__ __call__

class Singleton(type):
    def __init__(cls, name, bases, dic):
        super(Singleton, cls).__init__(name, bases, dic)
        cls.instance = None
        print("Singleton __init__")

    def __call__(cls, *args, **kwargs):
        print("Singleton __call__ before")
        if cls.instance is None:
            cls.instance = super(Singleton, cls).__call__(*args, **kwargs)
        print("Singleton __call__ after")
        return cls.instance


class Global(object):
    __metaclass__ = Singleton

    def __init__(self):
        print("Global __init__")


print("___________")
a = Global()
b = Global()

# Singleton __init__
# ___________
# Singleton __call__ before
# Global __init__
# Singleton __call__ after
# Singleton __call__ before
# Singleton __call__ after

references:

Creating a singleton in python

Stackoverflow上的Python问题精选

Clone this wiki locally