zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    .net实现浏览器大文件分片上传
    asp.net实现浏览器大文件分片上传
    php实现浏览器大文件分片上传
    Java实现浏览器大文件分片上传
    文件分片上传
    大文件分片上传
    pdf缩略图生成上传解决方案
    专业精神的三个步骤
    安卓TabHost+ViewPager+RadioGroup多功能模板整理
    java基础之概谈xml文件解析
  • 原文地址:https://www.cnblogs.com/jiangjing/p/8184299.html
Copyright © 2011-2022 走看看