欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python下__new__ __init__ __call__的详解

程序员文章站 2022-09-25 12:40:54
new __new__(cls, *args, **kwargs) 创建一个实例(通常是cls的,也可以是其他类型的实例) init __init__(self, *args...

new

__new__(cls, *args, **kwargs) 创建一个实例(通常是cls的,也可以是其他类型的实例)

init

__init__(self, *args, **Kwargs)

在实例被new创建后,返回给调用者前被执行

如果new返回的是cls的实例,那么init方法会被自动执行,self是创建的实例,init的入参和new的入参是一样的

If new() returns an instance of cls, then the new instance’s init() method will be invoked like init(self[, …]), where self is the new instance and the remaining arguments are the same as were passed to new().

如果new返回的不是cls的实例,那么init方法不会被执行

If new() does not return an instance of cls, then the new instance’s init() method will not be invoked.

new用于继承不可变类型,创建自定义的实例;也可以用来在自定义的元类中重写,创建自定的实例

new() is intended mainly to allow subclasses of immutable types (like int, str, or tuple) to customize instance creation. It is also commonly overridden in custom metaclasses in order to customize class creation.

call

__call__(self, *args, **Kwargs) 创建好的实例被调用时,触发;举个栗子,实例instance,执行instance()会触发call 即允许一个类的实例,可以像函数一样被调用

示例代码

new返回类自己的实例

class Bar(object):
    pass
class Foo(object):
    def __new__(cls, *args, **kwargs):
        print 'foo new'
        print 'args {}'.format(args)
        print 'kwargs {}'.format(kwargs)
        return super(Foo, cls).__new__(cls, *args, **kwargs)
    def __init__(self, *args, **kwargs):
        print 'foo init'
        print 'args {}'.format(args)
        print 'kwargs {}'.format(kwargs)
    def __call__(self, *args, **kwargs):
        print 'foo call'
        print 'args {}'.format(args)
        print 'kwargs {}'.format(kwargs)
foo = Foo('a', 1, other=['id', 'ip'])
foo(1, 2, 3, other=['a', 'b'])

foo new

args (‘a’, 1)

kwargs {‘other’: [‘id’, ‘ip’]}

foo init

args (‘a’, 1)

kwargs {‘other’: [‘id’, ‘ip’]}

foo call

args (1, 2, 3)

kwargs {‘other’: [‘a’, ‘b’]}

new不返回实例(init不会被执行, call被调用会报错)

# coding: utf-8
class Bar(object):
    pass
class Foo(object):
    def __new__(cls, *args, **kwargs):
        print 'foo new'
        print 'args {}'.format(args)
        print 'kwargs {}'.format(kwargs)
        # return super(Foo, cls).__new__(cls, *args, **kwargs)
    def __init__(self, *args, **kwargs):
        print 'foo init'
        print 'args {}'.format(args)
        print 'kwargs {}'.format(kwargs)
    def __call__(self, *args, **kwargs):
        print 'foo call'
        print 'args {}'.format(args)
        print 'kwargs {}'.format(kwargs)
foo = Foo('a', 1, other=['id', 'ip'])
# foo(1, 2, 3, other=['a', 'b']) # NonType object is not callable

foo new
args (‘a’, 1)
kwargs {‘other’: [‘id’, ‘ip’]}

new返回其他类型的实例(init不会被执行,call调用的是被返回的这个实例的)
# coding: utf-8
class Bar(object):
    def __call__(self, *args, **kwargs):
        print 'bar call'
class Foo(object):
    def __new__(cls, *args, **kwargs):
        print 'foo new'
        print 'args {}'.format(args)
        print 'kwargs {}'.format(kwargs)
        return Bar()
    def __init__(self, *args, **kwargs):
        print 'foo init'
        print 'args {}'.format(args)
        print 'kwargs {}'.format(kwargs)
    def __call__(self, *args, **kwargs):
        print 'foo call'
        print 'args {}'.format(args)
        print 'kwargs {}'.format(kwargs)
foo = Foo('a', 1, other=['id', 'ip'])
foo(1, 2, 3, other=['a', 'b'])

foo new

args (‘a’, 1)

kwargs {‘other’: [‘id’, ‘ip’]}

bar call

在继承不可变类型时newinit的区别

# coding: utf-8
class Foo(int):
    def __init__(self, *args, **kwargs):
        super(Foo, self).__init__(100)
foo = Foo(1)
# 在init中无法修改
print foo

1

# coding: utf-8
class Foo(int):
    def __new__(cls, *args, **kwargs):
        return super(Foo, cls).__new__(cls, 100)
foo = Foo(1)
# 在new中可以修改
print foo

100

在元类编程new的使用(元编程相关,之后会单独写一篇)

# coding: utf-8
class Foo(type):
    def __new__(cls, *args, **kwargs):
        ret = super(Foo, cls).__new__(cls, *args, **kwargs)
        return ret
class Bar():
    __metaclass__ = Foo
bar = Bar()
print bar