class attributes & data attributes

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Wed Jun 20 11:12:06 EDT 2007


james_027 a écrit :
> hi everyone,
> 
> I am now in chapter 5 of Dive Into Python and I have some question
> about it. From what I understand in the book is you define class
> attributes & data attributes like this in python

s/data/instance/

> class Book:
> 
>     total # is a class attribute
> 
>     def __init__(self):
>         self.title  # is a data attributes
>         self.author # another data attributes
> 
> To define class attributes is like defining a function in class, to
> define a data attributes is defining a variable inside the __init__
> method.
> 
> what makes me confuse is this model from Django
> 
> from django.db import models
> 
> class Person(models.Model):
>     first_name = models.CharField(maxlength=30)
>     last_name = models.CharField(maxlength=30)
> 
> I believe the first_name and last_name are data attributes? but why it
> is they look like a class attributes as being define.

first_name and last_name are actually class attributes. AFAICT, they are 
descriptors[1] controlling access to the resultset returned by the db query.

[1] cf the doc for the descriptor protocol on python.org. This is the 
feature that - amongst other things - allow Python to have a support for 
'computed attributes' (aka properties).



HTH



More information about the Python-list mailing list