1.(python)__new__与__init__

1.来比较一下__new__与__init__:

(1)__new__在初始化实例前调用,__init__在初始化实例之后调用,用来初始化实例的一些属性或者做一些初始操作

# -*- coding: utf-8 -*-
class Person(object):
    def __new__(cls, name, age):
        print '__new__ called.'
        return super(Person, cls).__new__(cls, name, age)
    def __init__(self, name, age):
        print '__init__ called.'
        self.name = name
        self.age = age
if __name__ == '__main__':
    piglei = Person('jiangjing', 25)

输出:

__new__ called.
__init__ called.
(2)如果__new__不返回实例,__init__方法就不会被调用

2.使用__new__方法来实现单例模式
(1)线程不安全的实现:
class Singleton(object):
    def __new__(cls):
        # 关键在于这,每一次实例化的时候,我们都只会返回这同一个instance对象
        if not hasattr(cls, 'instance'):
            cls.instance = super(Singleton, cls).__new__(cls)
        return cls.instance
obj1 = Singleton()
obj2 = Singleton()
obj1.attr1 = 'value1'
print obj1.attr1, obj2.attr1
print obj1 is obj2

(2)线程安全的实现:

# -*- coding: utf-8 -*-
import logging
import threading

Lock = threading.Lock()


class Singleton(object):

    # 定义静态变量实例
    __instance = None

    def __init__(self):
        pass

    def __new__(cls, *args, **kwargs):
        if not cls.__instance:
            try:
                Lock.acquire()
                # double check
                if not cls.__instance:
                    cls.__instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
            finally:
                Lock.release()
        return cls.__instance

if __name__ == "__main__":
    obj1 = Singleton()
    obj2 = Singleton()
    print id(obj1)
    print id(obj2)

输出:

139762690049616
139762690049616

 

posted on 2018-01-03 16:13  后端bug开发工程师  阅读(133)  评论(0编辑  收藏  举报

导航