• Python3的__new__进行构造类的实例化


    __new__方法

    1. 这个方法是用来生成类的实例
    class Singleton(object):
        def __new__(cls,*args, **kwargs): ①
            if not hasattr(cls,'_inst'):   
                print(cls)
                cls._inst = super(Singleton, cls).__new__(cls) ②
            return cls._inst ②
    

    ① 第一个参数必须是"要进行实例化的类".
    ② 返回实例完成的结果,如果实例化失败那么实例的初始化函数"init"肯定不会执行

    Python2(2.7)的写法

    class Singleton(object):
        def __new__(cls,*args, **kwargs): ①
            if not hasattr(cls,'_inst'):   
                print(cls)
                cls._inst = super(Singleton, cls).__new__(cls,*args,**kwargs) ②
            return cls._inst ②
    

    Python3(3.5)的写法

    class Singleton(object):
        def __new__(cls,*args, **kwargs): ①
            if not hasattr(cls,'_inst'):   
                print(cls)
                cls._inst = super(Singleton, cls).__new__(cls) ②
            return cls._inst ②
    

    如果Python3的写法跟Python2写法一样,那么倒数第二行会报错"TypeError: object() takes no parameters"

  • 相关阅读:
    内核态内存映射
    FS 数据结构
    内存页分配/释放
    用户态内存映射
    WindowsServer 2008 TIME_WAIT
    OutOfMemoryError:修改tomcat启动参数
    windows下Tomcat添加jmx监控
    mysql 5.7.11 安装运行
    mysql 数据库备份与还原
    Win7下虚拟WiFi设置
  • 原文地址:https://www.cnblogs.com/wspblog/p/7810707.html
Copyright © 2020-2023  润新知