class attribute
Todd Dembrey
todd.dembrey at gmail.com
Thu Jan 28 09:13:19 EST 2016
On 28/01/16 13:15, ast wrote:
> hello
>
> Here is a class from django framework
>
>
> from django.db import models
>
> class Article(models.Model):
>
> titre = models.CharField(max_length=100)
> auteur = models.CharField(max_length=42)
> contenu = models.TextField(null=True)
> date = models.DateTimeField(auto_now_add=True, auto_now=False,
> verbose_name="Date de parution")
>
> def __str__(self):
> return self.titre
>
> From a Python point of view, what are titre, auteur, contenu and date ?
> Are they class attributes, so common to all instance of Article ?
> It seems so to me.
>
> But if i do in a django shell (run with py manage.py shell)
>
>>>> Article.titre
>
> it doesnt work,
> AttributeError: type object 'Article' has no attribute 'titre'
> why ?
>
> if I test on a small class
>
>>>> class MyClass:
>>>> i=0
>>>>
>>>> MyClass.i
>>>> 0
>
> works
>
>
>
> When we create an object of class Article
>
> article = Article(titre="Bonjour", auteur="Maxime")
> article.contenu = "Les crêpes bretonnes sont trop bonnes !"
>
> we use the same names titre, auteur, contenu, which should be instance
> attribute this time. This is confusing to me
>
> thx
Django Model classes are very different from a basic Python classes. It
is worth having a look inside django/db/models/base.py for more
information. But in summary, see below.
The Model class has a metaclass of ModelBase which on __new__() returns
a class constructed from the attributes which you have defined in your
Model class (Article in this example). All the information is retained,
it is just filed away neatly for other purposes. Have a look in the
Article._meta attribute. You can find the fields you provided through
Article._meta.fields.
When you create Article (as above) you run the __init__() which reaches
into the ._meta attribute of the class in order to create an object,
which is then stored within the 'database'.
This is done because you don't want to access the attributes on the
Model, so they are removed when the Model is created. What you actually
want to do is access them on the objects within the Model. Writing
Article.objects.first().titre in Django Models is mostly equivalent to
Article.titre from Python classes.
Todd
More information about the Python-list
mailing list