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"

posted @ 2017-11-09 17:59  Dus  阅读(1693)  评论(0编辑  收藏  举报