【python教程入门学习】Python 中__new__方法详解及使用

144 阅读2分钟

new 的作用 在Python中__new__方法与__init__方法类似,但是如果两个都存在那么__new__闲执行。

在基础类object中,__new__被定义成了一个静态方法,并且需要传递一个参数cls。Cls表示需要实例化的类,此参数在实例化时由Python解析器自动提供。

new()是在新式类中新出现的方法,它作用在构造方法init()建造实例之前,可以这么理解,在Python 中存在于类里面的构造方法init()负责将类的实例化,而在init()调用之前,new()决定是否要使用该init()方法,因为new()可以调用其他类的构造方法或者直接返回别的对象来作为本类 的实例。

new()方法的特性: new()方法是在类准备将自身实例化时调用。

new()方法始终都是类的静态方法,即使没有被加上静态方法装饰器。对于新手小白想更轻松的学好Python基础,Python爬虫,web开发、大数据,数据分析,人工智能等技术,这里给大家分享系统教学资源,架下我尉(同英): 2763177065 【教程/工具/方法/解疑】

实例 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"