1. 程式人生 > >《笨方法學python》習題43分析

《笨方法學python》習題43分析

一、涉及函式

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.pywoainiwo bu ai niclassA(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.pywoainiwo bu ai niTraceback (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.pysdasdFdsfsdf9

return 返回值返回給函式a(),但是呼叫函式a,a()用列印兩行的功能。

附註3:

good_pod = randint(1,5)這樣寫,而不是random.randint(),因為有from random import randint

二、程式碼詳解:

1from sys import exit2 from random import randint34 classScene(object):56     def enter(self):7         print"This scene is not yet configured. Subclass it and implement enter()."8         exit(1)910 classEngine(object):1112     def __init__(self, scene_map):13         self.scene_map = scene_map1415     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。這裡能體會到因為類是模板只能賦給變數例項化後使用!1718         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,2223 classDeath(Scene):2425     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     ]3132     def enter(self): #隨機列印quips列表中0到3之間的也就是quips列表中的4句話,然後退出33         printDeath.quips[randint(0, len(self.quips)-1)]34         exit(1)3536 classCentralCorridor(Scene):3738     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."4849         action = raw_input("> ")5051         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’,跳line205960         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'6869         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'7778         else:79             print"DOES NOT COMPUTE!"80             return'central_corridor'8182 classLaserWeaponArmory(Scene):8384     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次數小於1097             print"BZZZZEDDD!"98             guesses +=1 #這個地方有個bug,因為line93輸入了一次密碼,而這個迴圈最多可以迴圈10次,就是輸入了11次密碼,但是我們本來的設計是10次!99             guess = raw_input("[keypad]> ")100101         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'112113 classTheBridge(Scene):114115     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."122123         action = raw_input("> ")124125         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'133134         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'144145         else:146             print"DOES NOT COMPUTE!"147             return'the_bridge'148149 classEscapePod(Scene):150151     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?"159160         good_pod = randint(1,5)161         guess = raw_input("[pod #]> ")162163         if int(guess) != good_pod:164             print"You jump into pod %s and hit the eject button." % guess165             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'169170         else:171             print"You jump into pod %s and hit the eject button." % guess172             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'178179 classMap(object):180181     scenes = {182             'central_corridor':CentralCorridor(),183             'laser_weapon_armory':LaserWeaponArmory(),184             'the_bridge':TheBridge(),185             'escape_pod':EscapePod(),186             'death':Death()187     }188189     def __init__(self, start_scene):190         self.start_scene = start_scene191192     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,194195     def opening_scene(self):196         returnself.next_scene(self.start_scene) #返回值為a_map呼叫next_scene()函式,引數為start_scene,start_scene被初始化為'central_corridor'197198 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。