python __new__ __init__ __call__详解

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值