1
2 """
3 Tutorial 05 - 对象遗传
4
5 你可以自由的从你期望的类 引导 出响应请求的类
6 另外,在实际应用中,常常需要建立 统一的基础类来处理所有页面统一的页头,页尾
7
8 """
9
10 from cherrypy import cpg
11
12 class Page:
13 """基础页面类
14 - 在类的属性中保存页面标题
15 """
16 title = 'Untitled Page'
17
18 def header(self):
19 return '''
20 <html>
21 <head>
22 <title>%s</title>
23 <head>
24 <body>
25 <h2>%s</h2>
26 ''' % (self.title, self.title)
27
28 def footer(self):
29 return '''
30 </body>
31 </html>
32 '''
33
34
35
36
37 class HomePage(Page):
38 """主页,使用不同的标题
39 """
40 title = 'Tutorial 5'
41
42 def __init__(self):
43 """初始化类,创建一个子页面
44 """
45 self.another = AnotherPage()
46
47 def index(self):
48 """注意,这里我们通过继承,调用header 和 footer
49 """
50 return self.header() + '''
51 <p>
52 Isn't this exciting? There's
53 <a href="./another/">another page</a>, too!
54 </p>
55 ''' + self.footer()
56
57 index.exposed = True
58
59
60 class AnotherPage(Page):
61 title = 'Another Page'
62 def __init__(self):
63 """发布下层对象
64 """
65 self.deep = DeepPage()
66 def index(self):
67 return self.header() + '''
68 <p>
69 And this is the amazing second page!
70 </p>
71 <hr/>
72 <a href="deep">deep page</a>
73 ''' + self.footer()
74
75 index.exposed = True
76
77 class DeepPage(Page):
78 """不支持堆叠的多层对象继承!!
79 - 比如说:
80 - class DeepPage(AnotherPage)
81 - 只能从 Page 对象继承,发布!
82 """
83 title = 'DeepPage base AnotherPage'
84
85 def __init__(self):
86 """发布下层对象
87 """
88 self.deep = LoopPage()
89 def index(self):
90 return self.header() + '''
91 <p>
92 这是第三层对象的发布!!
93 </p>
94 <hr/>
95 <a href="deep">deep page</a>
96 ''' + self.footer()
97
98 index.exposed = True
99
100 class LoopPage(Page):
101 title = 'LoopPage base AnotherPage'
102
103 def index(self):
104 return self.header() + '''
105 <p>
106 这是第4层对象的发布!!
107 </p>
108 ''' + self.footer()
109
110 index.exposed = True
111
112 cpg.root = HomePage()
113
114 cpg.server.start(configFile = 'tutorial.conf')
CherrPyTut/05_derived_objects.py (last edited 2009-12-25 07:14:57 by localhost)