2

I'm trying to understand how modelforms work in Django, so am going through the source code, and diagramming it out.

I'm stuck on this particular function in forms.widgets.py though, and I wonder if someone could explain it. Thank you.

What does the "type" argument mean? What are the args in "new"? I understand that this is returning a new class, but that's the extent of my comprehension.

Here is a link to the original code.

class MediaDefiningClass(type):
    """
    Metaclass for classes that can have media definitions.
    """
    def __new__(mcs, name, bases, attrs):
        new_class = super(MediaDefiningClass, mcs).__new__(mcs, name, bases, attrs)

        if 'media' not in attrs:
            new_class.media = media_property(new_class)

        return new_class
fstopzero
  • 1,073
  • 2
  • 10
  • 24
  • This is a metaclass. Metaclasses are a complex topic that have been covered thoroughly elsewhere. Look it up if you really want to know but be warned you are going deep into Python. – Alex Hall Apr 16 '16 at 23:13
  • Thanks. I started going down the road, and am hoping that understanding this in context will help make this concept a little more concrete and help me grasp it. – fstopzero Apr 16 '16 at 23:39

2 Answers2

1

type in that location means its a base class of the class. makes sense in that its defining a 'type of class' (classes defined to provide media).

new is the first step of instance creation. It's called first, and is responsible for returning a new instance of your class. In contrast, init doesn't return anything; it's only responsible for initializing the instance after it's been created.

Looks like the parameters for your new describe the new class by their names. the NAME specified in name, the base classes in bases and the attrs defined for the class in atters. but would need more code to be sure.

LhasaDad
  • 1,786
  • 1
  • 12
  • 19
1

This answer explains Python metaclasses and what type is

A metaclass is the class of a class. Like a class defines how an instance of the class behaves, a metaclass defines how a class behaves. A class is an instance of a metaclass.

type is the usual metaclass in Python. In case you're wondering, yes, type is itself a class, and it is its own type. ... To create your own metaclass in Python you really just want to subclass type.

Community
  • 1
  • 1
C14L
  • 12,153
  • 4
  • 39
  • 52