1

I am playing with metaclasses in Python 2.7. So I created a code that looks like this:

class M(type):
    def __new__(meta, name, parents, attrs):
        print 'In meta new'
        return super(meta, meta).__new__(meta, name, parents, attrs)

    def __init__(cls, *args, **kwargs):
        print 'In meta init'

    def __call__(cls, *attr, **val):
        print 'In meta call'
        return super(cls, cls).__new__(cls)

class A(object):
    __metaclass__ = M

    def __new__(cls):
        print 'In class new'
        return super(cls, cls).__new__(cls)

    def __init__(self):
        print 'In object init'

    def __call__(self):
        print 'In object call'

But the output confuses me:

A()

In meta new
In meta init
In meta call

Somehow class methods __ new __ and __ init __ were overridden, so interpreter just skip them. Can anyone explain this stuff?

Thanks for your help.

2 Answers 2

1

You're calling super() incorrectly. The first argument to super() is supposed to be the class itself, not the instance of it.

return super(meta, meta).__new__(meta, name, parents, attrs)

should be...

return super(M, meta).__new__(meta, name, parents, attrs)

and so on for the other super() calls - the first argument should be the class they're within; the second is the actual instance.

Sign up to request clarification or add additional context in comments.

Comments

0

It does not work because I do not use the origin Python mechanism - cls(), which guaranties automatic working of the __new__ and __init__ methods, it is overridden by metaclass __call__ method, which doesn't do the same.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.