Home > Backend Development > Python Tutorial > python中的__init__ 、__new__、__call__小结

python中的__init__ 、__new__、__call__小结

WBOY
Release: 2016-06-16 08:44:24
Original
1058 people have browsed it

1.__new__(cls, *args, **kwargs)  创建对象时调用,返回当前对象的一个实例;注意:这里的第一个参数是cls即class本身
2.__init__(self, *args, **kwargs) 创建完对象后调用,对当前对象的实例的一些初始化,无返回值,即在调用__new__之后,根据返回的实例初始化;注意,这里的第一个参数是self即对象本身【注意和new的区别】
3.__call__(self,  *args, **kwargs) 如果类实现了这个方法,相当于把这个类型的对象当作函数来使用,相当于 重载了括号运算符
 

看具体的例子:

复制代码 代码如下:

class O(object):

    def __init__(self, *args, **kwargs):
        print "init"
        super(O, self).__init__(*args, **kwargs)

    def __new__(cls, *args, **kwargs):
        print "new", cls
        return super(O, cls).__new__(cls, *args, **kwargs)

    def __call__(self,  *args, **kwargs):
        print "call"
      

    oo = O()
    print "________"
    oo() 


打印出来的是:
复制代码 代码如下:

new
init
________
call

比如:Python Singleton(单例模式)实现,那我们是不是只是重载一些__new__方法就可以了
复制代码 代码如下:

class Singleton1(object):
    """ 重载new方法"""
    def __new__(cls, *args, **kwargs):
        if not "_instance" in vars(cls):
            cls._instance = super(Singleton1, cls).__new__(cls, *args, **kwargs)
        return cls._instance

可不可以重载__init__方法呢?明显不可以,因为__init__之前调用了__new__方法,这时候已经生成了一个对象了,没办法实现单例模式

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template