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找不到ssl模块问题 No module named _ssl
下一篇:Python3时间戳转换为指定格式的日期

PythonTab微信公众号:

Python技术交流互助群 ( 请勿加多个群 ):

群1: 87464755

群2: 333646237

群3: 318130924

群4: 385100854