Python中_new_方法詳解及使用

_new_的做用
在python中_new_方法與_init_方法相似,可是若是兩都存在那麼_new_閒執行。
在基礎類object中,_new_被定義成了一個靜態方法,而且須要傳遞一個參數cls。Cls表示需實例化的類,此參數在實例化時由Python解析器自動提供。
new()是在新式類中新出現的方法,它做用在構造方法init()建造實例以前,能夠這麼理解,在Python 中存在於類裏面的構造方法init()負責將類的實例化,而在init()調用以前,new()決定是否要使用該init()方法,由於new()能夠調用其餘類的構造方法或者直接返回別的對象來做爲本類 的實例。 
New(方法的特性)
new()方法是在類準備將自身實例化時調用。 
new()方法始終都是類的靜態方法,即便沒有被加上靜態方法裝飾器。
實例
class Person(object):
  
    def __init__(self, name, age):
        self.name = name
        self.age = age
     
    def __new__(cls, name, age):
        if 0 < age < 150:
            return object.__new__(cls)
            # return super(Person, cls).__new__(cls)
        else:
            return None
  
    def __str__(self):
        return '{0}({1})'.format(self.__class__.__name__, self.__dict__)
  
print(Person('Tom', 10))
print(Person('Mike', 200))
結果:
Person({'age': 10, 'name': 'Tom'})
None
Python3和python2中_new_使用不一樣
Python2的寫法
注意python版本大於等於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的寫法
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"python

相關文章
相關標籤/搜索