Why is __metaclass__ not working?

After reading parts of the Django source code, I want to run some tests and write the codes below to see how the metaclass works :

class MyMeta(type):
    def __new__(cls, name, bases, attrs):
        print cls, name, bases, attrs
        return super(MyMeta, cls).__new__(cls, name, bases, attrs)

class AttrFiled(object): pass

class Test(MyMeta):
    name = AttrField()

He always complains:

TypeError: __new__() takes at least 2 arguments (1 given)

And I add to modify it, as shown below:

def with_metaclass(meta, *bases):  # copied from Django code.
    return meta("NewBase", bases, {})

class Test(with_metaclass(MyMeta)):
    name = CharField()

and it works.

I also read this. What is a metaclass in Python? . But still feel embarrassed.

Thanks in advance!

+4
source share
1 answer

with_metaclassIt was first introduced in the library six(if I remember correctly), which facilitates the transition from Python 2 to Python 3. This is a smart trick to make code compatible with both of them.

Python 2 :

class Foo(object):
    __metaclass__ = FooMeta

Python 3, :

class Foo(metaclass=FooMeta):
    pass

with_metaclass(meta) : , meta metaclass ', . , Pythons - 2 3 .

Python : http://docs.python.org/3/reference/datamodel.html#metaclasses


, class Test(MyMeta):, Test, MyMeta. ,

 class Test:
     __metaclass__ = MyMeta

 class Test(metaclass=MyMeta):
     ...

, python. , , Python 2 , with_metaclass, .

+4

All Articles