1、方法介绍
先看下在python的官方文档中对__new__
方法的介绍:
https://docs.python.org/3/reference/datamodel.html?highlight=new#object.new
如下:
Use __new__
when you need to control the creation of a new instance. Use __init__
when you need to control initialization of a new instance.
__new__
is the first step of instance creation. It's called first, and is responsible for returning a new instance of your class. In contrast, __init__
doesn't return anything; it's only responsible for initializing the instance after it's been created.
In general, you shouldn't need to override __new__
unless you're subclassing an immutable type like str, int, unicode or tuple.
总的来讲:
(1) __new__
方法控制了实例的创建过程,返回新创建的实例;
(2) __init__
方法控制的是实例的初始化过程,无返回值;
(3) __new__
的调用过程在__init__
之前;
2、使用场景
__new__
方法的使用中,其中一种是用作类的单例模式;
比如,在写python代码时,我常习惯将配置参数信息单独放在config.py
文件的Config
类中,而配置参数信息往往又需要是全局唯一的,因此需要将其设计为单例模式,参考代码如下:
class Config(object):
_instance = None
def __new__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = object.__new__(cls)
return cls._instance
def __init__(self):
pass
file_dir = './data'
max_seq_len = 32
网友评论