Skip to content Skip to sidebar Skip to footer

Django, Python, And Class Variables

I'm simultaneously learning Python while picking up Django. I'm familiar with many other languages. In the following code snippet, x is a class variable of class Foo. class Foo(obj

Solution 1:

Django models use a metaclass to alter what is normal class behaviour.

Use dir(Question) and you'll see there are different attributes on that class now. This is custom behaviour just for Django models however.

If you are curious you can study the metaclass __new__ method, but it does a lot of work specific to Object Relational Mapping tasks.


Solution 2:

Magic.

No, really.

Python classes aren't set-in-stone structure, like they are in C++. They are, themselves, just objects — instances of another type:

class Foo(object):
    pass

print(type(Foo))  # <class 'type'>

You can even make a class like you'd make any other object, by calling type. This:

class Bar(object):
    a = 1
    b = 2

Is really (more or less) syntactic sugar for this:

Bar = type('Bar', (object,), {'a': 1, 'b': 2})

type takes the name of your new class, a list of its superclasses, and a dict of all the attributes of the class, and spits out a new class.

But, because type is just a class like any other, it's possible to subclass it and give it different behavior. And this is what Django has done: it's created a subclass of type that does something different with the dict of attributes you pass to it.

You don't see this happening directly in your own code, but if you check type(models.Model), you'll find out its type is not type, but something specific to Django. It probably has "meta" in the name, because it's called a metaclass: the class of a class.

This is a fairly common pattern for making "declarative" libraries in Python, where the attributes of a class actually define some kind of structure. You can see the same thing in form validation (wtforms), schema validation (colander), other ORMs (sqlalchemy), and even the stdlib enum module.


Solution 3:

Question is an object of type type. You want an instance of Question:

>>> q= Question(text = "Does a dog have the buddha nature?")

Then you should get

q.text "Does a dog have the buddha nature?"

Note that this object will not persist unless you save() it:

>>> q.save()

Post a Comment for "Django, Python, And Class Variables"