Background Image
Table of Contents Table of Contents
Previous Page  362 / 478 Next Page
Information
Show Menu
Previous Page 362 / 478 Next Page
Page Background

lists/models.py (ch18l025).

@property

def

name

(

self

):

return

self

.

item_set

.

first

()

.

text

The @property Decorator in Python

If you haven’t seen it before, the

@property

decorator transforms a method on a class

to make it appear to the outside world like an attribute.

This is a powerful feature of the language, because it makes it easy to implement “duck

typing”, to change the implementation of a property without changing the interface of

the class. In other words, if we decide to change

.name

into being a “real” attribute on

the model, which is stored as text in the database, then we will be able to do so entirely

transparently—as far as the rest of our code is concerned, they will still be able to just

access

.name

and get the list name, without needing to know about the implementation.

Of course, in the Django template language,

.name

would still call the method even if it

didn’t have

@property

, but that’s a particularity of Django, and doesn’t apply to Python

in general…

And that, believe it or not, actually gets us a passing test, and a working “My Lists” page

( Figure 18-1

)!

Figure 18-1. The “My Lists” page, in all its glory (and proof I did test on Windows)

334

|

Chapter 18: Finishing “My Lists”: Outside-In TDD