《笨方法学python》习题43的学习笔记

来源:互联网 发布:深圳压寨网络是培训么 编辑:程序博客网 时间:2024/05/19 22:00

一、涉及函数

1、Python 字典(Dictionary) get()方法

描述

Python 字典(Dictionary) get() 函数返回指定键的值,如果值不在字典中返回默认值。

语法

get()方法语法:

dict.get(key, default=None)

参数

  • key -- 字典中要查找的键。
  • default -- 如果指定键的值不存在时,返回该默认值值
返回值

返回指定键的值,如果值不在字典中返回默认值None。

实例dict = {'Name': 'Zara', 'Age': 27}
print "Value : %s" % dict.get('Age')
print "Value : %s" % dict.get('Sex', "Never")

以上实例输出结果为:

Value:27Value:Never

2、附注1:

不同类模板可以实例给同一个变量名。
代码测试如下:
classA(object):defasd(self):
print"woaini"classB(object):
defdas(self):
print"wo bu ai ni "
pooop=A()
pooop.asd()
pooop=B()
pooop.das()
输出结果:
PS C:\Users\Douhh\mystuff> python cs.py
woaini
wo bu ai ni

classA(object):
defasd(self):
print"woaini"
classB(object):
defdas(self):
print"wo bu ai ni "
pooop=A()
pooop.asd()
pooop=B()
pooop.das()
pooop.asd()
运行结果为:
PS C:\Users\Douhh\mystuff> python cs.py
woaini
wo bu ai ni
Traceback (most recent call last):
File "cs.py", line 11, in <module>
pooop.asd()
AttributeError: 'B' object has no attribute 'asd'
总结:不同类模板可以实例给同一个变量名,如例子,A类实例化为pooop后,B类也实例化为pooop,此时pooop是B类的实例化对象,此时的pooop只能调用B类没有A类的属性。

附注2:


def a():
print"sdasd"
print"Fdsfsdf"
return 4+5b=a()
print b
运行结果:
PS C:\Users\Douhh\mystuff> python cs1.py
sdasd
Fdsfsdf
9

return 返回值返回给函数a(),但是调用函数a,a()用打印两行的功能。

附注3:

good_pod = randint(1,5)这样写,而不是random.randint(),因为有from random import randint

二、代码详解:

1from sys import exit
2 from random import randint
3
4 classScene(object):
5
6     def enter(self):
7         print"This scene is not yet configured. Subclass it and implement enter()."
8         exit(1)
9
10 classEngine(object):
11
12     def __init__(self, scene_map):
13         self.scene_map = scene_map
14
15     def play(self):
16         current_scene =self.scene_map.opening_scene()# current_scene=a_game调用属性scene_map,因为scene_map=a_map,a_map可以继续调用自己的属性或者函数def opening_scene(self): line196 ,返回值为CentralCorridor()类,将其赋给current_scene变量。实例化一个CentralCorridor()类为current_scene。这里能体会到因为类是模板只能赋给变量实例化后使用!
17
18         whileTrue:
19             print"\n--------"
20             next_scene_name = current_scene.enter()#current_scene调用enter()函数 ,跳line38,next_scene_name=’death‘
21             current_scene =self.scene_map.next_scene(next_scene_name) #current_scene=a_game调用scene_map=a_map,a_map调用自己的函数next_scene(),参数为next_scene_name='death',跳line193,实例化了Death()类为current_scene,(见附注1),重复这个循环,next_scene_name=实例化了Death()类为current_scene调用enter()函数,跳line32,
22
23 classDeath(Scene):
24
25     quips = [
26             "You died. You kinda suck at this.",
27             "Your mon would be proud...if she were smarter.",
28             "Such a luser.",
29             "I have a small puppy that's better at this."
30     ]
31
32     def enter(self): #随机打印quips列表中0到3之间的也就是quips列表中的4句话,然后退出
33         printDeath.quips[randint(0, len(self.quips)-1)]
34         exit(1)
35
36 classCentralCorridor(Scene):
37
38     def enter(self):
39         print"The Gothons of Planet Percal #25 have invaded your ship and destroyed"#打印了数行文字
40         print"your entire crew. You are the last surviving member and your last"
41         print"mission is to get the neutron destruct bomb from the Weapons Armory,"
42         print"put it in the bridge, and blow the ship up after getting into an "
43         print"escape pod.\n"
44         print"You're running down the central corridor to the Weapons Armory when"
45         print"a Gothon jumps out, red scaly skin, dark grimy teeth, and evil clown costume"
46         print"flowing around his hate filled body. He's blocking the door to the"
47         print"Armory and about to pull a weapon to blast you."
48
49         action = raw_input("> ")
50
51         if action =="shoot!":
52             print"Quick on the draw you yank out your blaster and fire it at the Gothon."
53             print"His clown costume is flowing and moving around his body, which throws"
54             print"off your aim. Your laser hits his costume but misses him entirely. This"
55             print"completely ruins his brand new costume his mother bought him, which"
56             print"makes him fly into an insane rage and blast you repeatly in the face until"
57             print"you are dead. Then he eats you."
58             return'death'#若返回‘death’,跳line20
59
60         elif action =="dodge!":
61             print"Like a world class boxer you dodge, weave, slip and slide right"
62             print"as the Gothon's blaster cranks a laser past your head."
63             print"In the middle of your artful dodge your foot slips and you"
64             print"bang your head on the metal wall and pass out."
65             print"You wake up shortly after only to die as the Gothon stomps on"
66             print"your head and eats you."
67             return'death'
68
69         elif action =="tell a joke":
70             print"Lucky for you they made you learn Gothon insults in the academy."
71             print"You tell the one Gothon joke you know."
72             print"Lbhe zbgure vf fb sng, jura fur fvgf nebhaq gur ubhfr, fur fvgf nebhaq gur ubhfr."
73             print"The Gothon stops, tries not to laugh, then busts out laughing and can't move."
74             print"While he's laughing you run up and shoot him square in the head"
75             print"putting him down, then jump through the Weapon Armory door."
76             return'laser_weapon_armory'
77
78         else:
79             print"DOES NOT COMPUTE!"
80             return'central_corridor'
81
82 classLaserWeaponArmory(Scene):
83
84     def enter(self):
85         print"You do a dive roll into the Weapon Armory, crouch and scan the room"
86         print"for more Gothons that might be hiding. It's dead quiet, too quiet."
87         print"You stand up and run to the far side of the room and find the "
88         print"neutron bomb in its container. There's a keypad lock on the box"
89         print"and you need the code to get the bomb out. If you get the code"
90         print"wrong 10 times then the lock closes forever and you can't "
91         print"get the bomb. The code is 3 digits."
92         code ="%d%d%d" % (randint(1,9), randint(1,9), randint(1,9)) #code=随机三位数
93         guess = raw_input("[keypad]> ")
94         guesses =0 #计次数
95         
96         while guess != code and guesses <10:#False值条件为guess=codeguesses次数小于10
97             print"BZZZZEDDD!"
98             guesses +=1 #这个地方有个bug,因为line93输入了一次密码,而这个循环最多可以循环10次,就是输入了11次密码,但是我们本来的设计是10次!
99             guess = raw_input("[keypad]> ")
100
101         if guess == code:
102             print"The container clicks open and the seal breaks, letting gas out."
103             print"You grab the neutron bomb and run as fast as you can to the "
104             print"bridge where you must place it in the right spot."
105             return'the_bridge'
106         else:
107             print"The lock buzzes one last time and then you hear a sickening"
108             print"melting sound as the mechanism is fused together."
109             print"You decide to sit there, and finally the Gothons blow up the"
110             print"ship from their ship and you die."
111             return'death'
112
113 classTheBridge(Scene):
114
115     def enter(self):
116         print"You burst onto the Bridge with the netron destruct bomb"
117         print"under your arm and surprise 5 Gothons who are trying to"
118         print"take control of the ship. Each of them has an even uglier"
119         print"clown costume than the last. They haven't pulled their"
120         print"weapons out yet, as they see the active bomb under your"
121         print"arm and don't want to set it off."
122
123         action = raw_input("> ")
124
125         if action =="throw the bomb":
126             print"In a panic you throw the bomb at the group of Gothons"
127             print"and make a leap for the door. Right as you drop it a"
128             print"Gothon shoots you right in the back killing you."
129             print"As you die you see another Gothon frantically try to disarm"
130             print"the bomb. You die knowing they will probably blow up when"
131             print"it goes off."
132             return'death'
133
134         elif action =="slowly place the bomb":
135             print"You point your blaster at the bomb under your arm"
136             print"and the Gothons put their hands up and start to sweat."
137             print"You inch backward to the door, open it, and then carefully"
138             print"place the bomb on the floor, pointing your blaster at it."
139             print"You then jump back through the door, punch the close button"
140             print"and blast the lock so the Gothons can't get out."
141             print"Now that the bomb is placed you run to the escape pod to"
142             print"get off this tin can."
143             return'escape_pod'
144
145         else:
146             print"DOES NOT COMPUTE!"
147             return'the_bridge'
148
149 classEscapePod(Scene):
150
151     def enter(self):
152         print"You rush through the ship desperately trying to make it to"
153         print"the escape pod before the whole ship explodes. It seems like"
154         print"hardly any Gothons are on the ship, so your run is clear of "
155         print"interference. You get to the chamber with the escape pods, and"
156         print"now need to pick one to take. Some of them could be damaged"
157         print"but you don't have time to look. There's 5 pods, which one"
158         print"do you take?"
159
160         good_pod = randint(1,5)
161         guess = raw_input("[pod #]> ")
162
163         if int(guess) != good_pod:
164             print"You jump into pod %s and hit the eject button." % guess
165             print"the pod escapes out into the void of space, then "
166             print"implodes as the hull ruptures, crushing your body"
167             print"into jam jelly."
168             return'death'
169
170         else:
171             print"You jump into pod %s and hit the eject button." % guess
172             print"The pod easily slides out into space heading to"
173             print"the planet below. As it flies to the planet, you look"
174             print"back and see your ship implode then explode like a "
175             print"bright star, taking out the Gothons ship at the same"
176             print"time. You won!"
177             return'finished'
178
179 classMap(object):
180
181     scenes = {
182             'central_corridor':CentralCorridor(),
183             'laser_weapon_armory':LaserWeaponArmory(),
184             'the_bridge':TheBridge(),
185             'escape_pod':EscapePod(),
186             'death':Death()
187     }
188
189     def __init__(self, start_scene):
190         self.start_scene = start_scene
191
192     def next_scene(self, scene_name):
193         returnMap.scenes.get(scene_name) #next_scene()函数返回值为Map类内部调用自己的属性scenes字典,get()获取key'central_corridor'对应的value为CentralCorridor(),返回值为CentralCorridor()类,跳line16,返回值为get()获取’death‘对应的值Death()类,跳line21,
194
195     def opening_scene(self):
196         returnself.next_scene(self.start_scene) #返回值为a_map调用next_scene()函数,参数为start_scene,start_scene被初始化为'central_corridor'
197
198 a_map =Map('central_corridor') #实例化一个Map()类为a_map对象,自动调用__init__函数,start_scene='central_corridor'。
199 a_game =Engine(a_map) #实例化一个Engine()类为a_game对象,自动调用__init__函数,scene_map=a_map,a_map是一个实例化对象,带有类Map的属性和函数。
200 a_game.play() #a_game对象调用函数play()


结语:这是我写在有道云笔记中直接copy过来的,所以格式很丑,最近正准备练习使用Markdown。