Debian Codegraph @

docs/recipes/inheritance.rst

raw
1 Basic Inheritance
2 =================
3
4 Introduction
5 ------------
6 Cheetah, like Python, is an object-oriented language if you so choose to
7 use it in that fashion. That is to say that you can use Cheetah in with
8 object-oriented principles *or* you can use Cheetah in a strictly functional
9 sense, like Python, Cheetah does not place restrictions on these barriers.
10
11 While Cheetah is not strictly Python, it was designed as such to interoperate,
12 particularly with the notion of classes, with Python itself. In effect you can
13 define Python classes that inherit and extend from Cheetah-derived classes and
14 vice versa. For this, Cheetah defines a few **directives** (denoted with the `\#`
15 hash-mark) that are of some help, the most important one being the `\#extends`
16 directive, with others playing important roles like `\#import`, `\#attr` and `\#super`
17
18 In this recipe/tutorial I intend to explain and define a few key inheritance
19 patterns with Cheetah, being:
20
21 * A Cheetah Template inheriting from Python
22 * Python inheriting from a Cheetah Template
23 * Cheetah Templates and "*mixins*"
24
25 This document also operates on the assumption that the reader is at least
26 somewhat familiar with the basic tenets of object-oriented programming in
27 Python.
28
29
30 Cheetah inheriting from Python
31 ------------------------------
32 Whether or not you are aware of it, Cheetah templates are always inheriting from
33 a Python class by default. Unless otherwise denoted, Cheetah templates are compiled
34 to Python classes that subclass from the `Cheetah.Template.Template` class.
35
36 What if you would like to introduce your own Template base class? Easily acheived by
37 defining your own Template class in a Python module, for example::
38
39 import Cheetah.Template
40
41 class CookbookTemplate(Cheetah.Template.Template):
42 _page = 'Cookbook'
43 author = 'R. Tyler Ballance'
44 def pageName(self):
45 return self._page or 'Unknown'
46
47 **Figure 1. cookbook.py**
48
49 For this example, I want all my subclasses of the `CookbookTemplate` to define a
50 page author which will be used in some shared rendering code, to accomplish this
51 my templates will need to subclass from `CookbookTemplate` explicitly instead of
52 implicitly subclassing from `Cheetah.Template.Template`::
53
54 #import cookbook
55 #extends cookbook.CookbookTemplate
56 #attr author = 'Tavis Rudd'
57
58 ## The rest of my recipe template would be below
59
60 **Figure 2. recipe1.tmpl**
61
62