习题38:列表的操作
当你看到像 mystuff.append('hello') 这样的代码时,你事实上已经在 Python 内部激发了一个连锁反应。以下是它的工作原理:
1. Python 看到你用到了 mystuff ,于是就去找到这个变量。也许它需要倒着检查看你有没有在哪里用 = 创建过这个变量,或者检查它是不是一个函数参数,或者看它是不是一个全局变量。不管哪种方式,它得先找到 mystuff 这个变量才行。
2. 一旦它找到了 mystuff ,就轮到处理句点 . (period) 这个操作符,而且开始查看 mystuff内部的一些变量了。由于 mystuff 是一个列表,Python 知道mystuff 支持一些函数。
3. 接下来轮到了处理 append 。Python 会将 “append” 和 mystuff 支持的所有函数的名称一一对比,如果确实其中有一个叫 append 的函数,那么 Python 就会去使用这个函数。
4. 接下来 Python 看到了括号 ( (parenthesis) 并且意识到, “噢,原来这应该是一个函数”,到了这里,它就正常会调用这个函数了,不过这里的函数还要多一个参数才行。
5. 这个额外的参数其实是…… mystuff! 我知道,很奇怪是不是?不过这就是 Python 的工作原理,所以还是记住这一点,就当它是正常的好了。真正发生的事情其实是append(mystuff, 'hello') ,不过你看到的只是 mystuff.append('hello')。
代码:
ten_things = "Apples Oranges Crows Telephone Light Sugar"
print "Wait there's not 10 things in that list, let's fix that."
stuff = ten_things.split(' ')
more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"]
while len(stuff) != 10:
next_one = more_stuff.pop()
print "Adding: ", next_one
stuff.append(next_one)
print "There %d items now." % len(stuff)
print "There we go: ", stuff
print "Let's do some things with stuff."
print stuff[1]
print stuff[-1] # whoa! fancy
print stuff.pop()
print ' '.join(stuff) # what? cool!
print '#'.join(stuff[3:5]) # super stellar!
结果:
习题39:字典,可爱的字典
代码:
cities = {
'CA': 'San Francisco',
'MI': 'Detroit',
'FL': 'Jacksonville'
}
cities['NY'] = 'New York'
cities['OR'] = 'Portland'
def find_city(themap, state):
if state in themap:
return themap[state]
else:
return "Not found."
# ok pay attention!
cities['_find'] = find_city
while True:
print "State? (Enter to quit)",
state = raw_input("> ")
if not state: break
# this line is the most important ever! study!
city_found = cities['_find'](cities, state)
print city_found
结果:
习题40:模块、类、对象
Python 里边有这么一个通用的模式:
1. 拿一个类似 key=value 风格的数据容器
2. 通过 key 的名称获取其中的 value
对于字典来说,key 是一个字符串,获得值的语法是 [key] 。对于模块来说,key是函数或者变量的名
称,而语法是 .key
现在我有三种方法可以从某个东西里获取它的内容:
# dict style
mystuff['apples']
# module style
mystuff.apples()
print mystuff.tangerine
# class style
class MyStuff(object):
def __init__(self):
self.tangerine = "And now a thousand years between"
def apple(self):
print "I AM CLASSY APPLES!"
thing = MyStuff()
thing.apples()
print thing.tangerine
第一行代码就是“实例化”操作,这和调用函数很相似。然而,当你进行实例化操作时,Python 在背后做了一系列的工作,这里我针对上面的代码详细解释一下:
1. Python 看到了 MyStuff() 并且知道了它是你定义过的一个类。
2. Python 创建了一个空的对象,里边包含了你在类中用 def 创建的所有函数。
3. 然后 Python 回去检查你是不是在里边创建了一个 __init__ 魔法函数,如果你有创建,它就会调用这个函数,从而对你的空对象实现了初始化。
4. 在 MyStuff 中的 __init__ 函数里,我们有一个多余的函数叫做 self ,这就是 Python 为我们创建的空对象,而我可以对它进行类似模块、字典等的操作,为它设置一些变量进去。
5. 在这里,我把 self.tangerine 设成了一段歌词,这样我就初始化了该对象。
6. 最后 Python 将这个新建的对象赋给一个叫 thing 的变量,以供后面使用。
代码:
class Song(object):
def __init__(self, lyrics):
self.lyrics = lyrics
def sing_me_a_song(self):
for line in self.lyrics:
print line
happy_bday = Song(["Happy birthday to you",
"I don't want to get sued",
"So I'll stop right there"])
bulls_on_parade = Song(["They rally around the family",
"With pockets full of shells"])
happy_bday.sing_me_a_song()
bulls_on_parade.sing_me_a_song()
结果:
习题41:物以类聚
代码:
class TheThing(object):
def __init__(self):
self.number = 0
def some_function(self):
print "I got called."
def add_me_up(self, more):
self.number += more
return self.number
# two different things
a = TheThing()
b = TheThing()
a.some_function()
b.some_function()
print a.add_me_up(20)
print b.add_me_up(30)
print a.number
print b.number
# Study this. This is how you pass a variable
# from one class to another/ You will need this.
class TheMultiplier(object):
def __init__(self, base):
self.base = base
def do_it(self, m):
return m * self.base
x = TheMultiplier(a.number)
print x.do_it(b.number)
结果:
代码2:-- 尚未完全理解,后续通过其他文档加深理解
from sys import exit
from random import randint class Game(object): def __init__(self, start): self.quips = [ "You died. You kinda suck at this.", "Your mom would be proud. If she were smarter.", "Such a luser.", "I have a small puppy that's better at this." ] self.start = start def play(self): next = self.start while True: print "\n--------" room = getattr(self, next) next = room() def death(self): print self.quips[randint(0, len(self.quips)-1)] exit(1) def central_corridor(self): print "The Gothons of Planet Percal #25 have invaded your ship and destroyed" print "your entire crew. You are the last surviving member and your last" print "mission is to get the neutron destruct bomb from the Weapons Armory," print "put it in the bridge, and blow the ship up after getting into an " print "escape pod." print "\n" print "You're running down the central corridor to the Weapons Armory when" print "a Gothon jumps out, red scaly skin, dark grimy teeth, and evil clown costume" print "flowing around his hate filled body. He's blocking the door to the" print "Armory and about to pull a weapon to blast you." action = raw_input("> ") if action == "shoot!": print "Quick on the draw you yank out your blaster and fire it at the Gothon." print "His clown costume is flowing and moving around his body, which throws" print "off your aim. Your laser hits his costume but misses him entirely. This" print "completely ruins his brand new costume his mother bought him, which" print "makes him fly into an insane rage and blast you repeatedly in the face until" print "you are dead. Then he eats you." return 'death' elif action == "dodge!": print "Like a world class boxer you dodge, weave, slip and slide right" print "as the Gothon's blaster cranks a laser past your head." print "In the middle of your artful dodge your foot slips and you" print "bang your head on the metal wall and pass out." print "You wake up shortly after only to die as the Gothon stomps on" print "your head and eats you." return 'death' elif action == "tell a joke": print "Lucky for you they made you learn Gothon insults in the academy." print "You tell the one Gothon joke you know:" print "Lbhe zbgure vf fb sng, jura fur fvgf nebhaq gur ubhfr, fur fvgf nebhaq gur ubhfr." print "The Gothon stops, tries not to laugh, then busts out laughing and can't move." print "While he's laughing you run up and shoot him square in the head" print "putting him down, then jump through the Weapon Armory door." return 'laser_weapon_armory' else: print "DOES NOT COMPUTE!" return 'central_corridor' def laser_weapon_armory(self): print "You do a dive roll into the Weapon Armory, crouch and scan the room" print "for more Gothons that might be hiding. It's dead quiet, too quiet." print "You stand up and run to the far side of the room and find the" print "neutron bomb in its container. There's a keypad lock on the box" print "and you need the code to get the bomb out. If you get the code" print "wrong 10 times then the lock closes forever and you can't" print "get the bomb. The code is 3 digits." code = "%d%d%d" % (randint(1,9), randint(1,9), randint(1,9)) guess = raw_input("[keypad]> ") guesses = 0 while guess