一、涉及函数

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 : 27 Value : Never

2、附注1:

不同类模板可以实例给同一个变量名。
代码测试如下:
class A (object): def asd (self):
print "woaini" class B (object):
def das (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
class A (object):
def asd (self):
print "woaini"
class B (object):
def das (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+5 b =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

二、代码详解:

1 from sys import exit
2 from random import randint
3
4 class Scene (object):
5
6     def enter( self ):
7         print "This scene is not yet configured. Subclass it and implement enter()."
8         exit( 1 )
9
10 class Engine (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         while True :
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 class Death ( 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         print Death .quips[randint( 0 , len( self .quips) -1 )]
34         exit( 1 )
35
36 class CentralCorridor ( 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 class LaserWeaponArmory ( 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=code 与 guesses次数小于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 class TheBridge ( 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 class EscapePod ( 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 class Map (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         return Map .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         return self .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。

《笨方法学python》习题43分析相关推荐

  1. 17.笨方法学python 习题43

    这章断断续续续写了一周,今天放出来......主要是翻译那些场景描述很烦人,毕竟0级英语. 面向对象的分析和设计的基本流程: 把要解决的问题写下来,或者画下来 将第一条的关键概念提取出来并加以研究 创 ...

  2. 笨方法学python 习题37

    还是在笨方法学python中... 本节的习题是看一下作者列出的python中的各种运算符,尝试来理解这些符号. 在这里,我只列出了一些自己不会的,通过查百度得到得答案,这里来列举一下. (另外有不怎 ...

  3. 笨方法学python习题4

    变量和命名 #笨方法学python_习题4#定义变量 cars = 100 space_in_a_car = 4.0 drivers = 30 passengers = 90#计算 cars_not_ ...

  4. python手记(游戏) 笨方法学python习题36【持续更新中】

    如有意见或其他问题可在下方写下评论或加QQ:1693121186 欢迎一起讨论技术问题! 代码如下: 解说:这是笨方法的习题36,让做一个游戏.我会持续更新,如果想复制玩玩的同学,请别将主线线人以下的 ...

  5. 笨方法学Python 习题 42: 对象、类、以及从属关系

    有一个重要的概念你需要弄明白,那就是"类(class)"和"对象(object)"的区别.问题在于,class 和 object 并没有真正的不同.它们其实是同 ...

  6. python数值运算答案_笨方法学Python 习题3:数字和数学计算

    数字和数学计算 print("I will now count my chickens") print("Hens",25+30/6) print(" ...

  7. python38使用_笨方法学Python 习题38:列表的操作

    列表的操作: 这里先复习一下之前遇见过的函数:split()通过指定分隔符对字符串进行切片,如果参数num有指定值,则仅分隔num个子字符 str.split(str="", nu ...

  8. 笨方法学python 习题26

    习题26 python:3.9 首先我不知道为什么书中的网站打不开,一直是404,所以我就去网上涨了源代码,如下 def break_words(stuff):"""Th ...

  9. 笨方法学python 习题34

    习题34 python:3.9 animals = ['bear','python','peacock','kangaroo','whale','platypus']print ("The ...

  10. 笨方法学python 习题29-31

    if & else 习题29 - if语句 代码如下: 结果输出: Tips: if语句是什么?有什么用处? +=是什么意思? 习题30 else和if 代码如下: 结果输出: Tips: 习 ...

最新文章

  1. 建立普通用户信任关系,
  2. Intel Realsense 如何获取输入图像的分辨率参数?傻办法 asanyarray() shape() get_data()
  3. 1、程序员常用工具网站
  4. SQL查询中having和where的异同点
  5. HTMLParser-实战
  6. 阿里云Kubernetes容器服务上体验Knative
  7. MySQL 5.5 手册下载
  8. TurboMail优势特点
  9. php with openssl directory,为php打扩展openssl 详细步骤
  10. iSPRINT:Google 最高能的创新加速课程,绝不允许产品走弯路!
  11. yii2 linkpager ajax,Yii2扩展 - LinkPager 带分页大小
  12. cad查看_CAD快速看图 for mac(CAD图纸查看工具) v4.3.7中文版
  13. 香港自由行攻略(自用)
  14. unity相机旋转带阻尼效果
  15. Java常量池[乐乐独记]
  16. 生死看淡,不服就GAN(六)----用DCGAN生成马的彩色图片
  17. mysql 索引方法_mysql索引方式
  18. 阿里云智能身份证OCR文字识别
  19. Git命令的使用(进阶版)
  20. 歌德巴赫猜想:任意一个大于等于6的偶数都能拆分为2个质数之和:如:8=3+5 求证6到1000内的所有偶数都成立

热门文章

  1. MongoDB安装(新版本保姆级教程)
  2. 2019全年营收净利润双超预期 微盟开启“飞轮模式”
  3. 稀疏表征:稀疏字典构建
  4. java毕业论文_【毕业论文】基于java的博客网站设计与开发毕业论文(word文档)
  5. xp系统如何查看计算机用户,xp查看电脑配置、查看电脑型号详细教程和命令
  6. vue+Element做表格的批量增加
  7. FME大规模转换OSM PBF数据
  8. 在家做什么兼职最靠谱?不去上班做什么好?
  9. 数据统计分析软件介绍
  10. 电路设计经验总结(以软件cadence allegro为例)