美文网首页
Python __new__方法的理解与使用

Python __new__方法的理解与使用

作者: lzhenboy | 来源:发表于2020-03-27 15:28 被阅读0次

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

相关文章

网友评论

      本文标题:Python __new__方法的理解与使用

      本文链接:https://www.haomeiwen.com/subject/exwluhtx.html