Using the __call__ method of a metaclass instead of __new__?

前端 未结 5 1342
情歌与酒
情歌与酒 2020-11-30 21:40

When discussing metaclasses, the docs state:

You can of course also override other class methods (or add new methods); for example defining a custom

5条回答
  •  长情又很酷
    2020-11-30 22:30

    It's a matter of lifecycle phases and what you have access to. __call__ gets called after __new__ and is passed the initialization parameters before they get passed on to __init__, so you can manipulate them. Try this code and study its output:

    class Meta(type):
        def __new__(cls, name, bases, newattrs):
            print "new: %r %r %r %r" % (cls, name, bases, newattrs,)
            return super(Meta, cls).__new__(cls, name, bases, newattrs)
    
        def __call__(self, *args, **kw):
            print "call: %r %r %r" % (self, args, kw)
            return super(Meta, self).__call__(*args, **kw)
    
    class Foo:
        __metaclass__ = Meta
    
        def __init__(self, *args, **kw):
            print "init: %r %r %r" % (self, args, kw)
    
    f = Foo('bar')
    print "main: %r" % f
    

提交回复
热议问题