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"


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM