您的位置:首页 > 编程语言 > Python开发

笨方法学python 42课笔记:物以类聚

2017-10-27 15:29 134 查看
代码1:

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

a = TheThing()
b = TheThing()

a.some_function()
b.some_function()

print a.add_me_up(20)
print a.add_me_up(20)
print b.add_me_up(30)
print b.add_me_up(30)

print a.number
print 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 smaarter.",
"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 Per cal #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 Gothonsjumps 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, which0"
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 slip 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 square in the head"
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 Goothons that might be hiding. It's fead 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 "wrooong 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 != code and guesses < 10:
print "BZZZZEDDD!"
guesses += 1
guess = raw_input("[keypad]> ")

if guess == code:
print "The container clicks open and the seal breaks, letting gas out."
print "You grab the neutron bomb and run as fast as you can to the"
print "bridge where you must place it in the right spot."
return 'the_bridge'

else:
print "The lock buzzes one last time and then you hear a sickening"
print "melting sound as the mechanism is fused together."
print "You decide to sit there, and finally the Gothons blow up the"
print "ship from their ship and you die."
return 'death'

def the_bridge(self):
print "You burst onto Bridge with the netron destruct bomb"
print "under your arm and surprise 55 Gothons who sre trying to"
print "take control of the ship. Each of them has an even uglier"
print "clown costume than the last. They haven't pulled their"
print "arm and don't want to set it off."

action = raw_input("> ")

if action == "throw the bomb":
print "In a panic you throw the bomb at the group of Gothons"
print "and make a leap for the door. Right as you drop it a"
print "Gothon shoots you right in the back killing you."
print "As you die you see anothor Gothon frantically try to disarm"
print "the bomb. You die knowing they will probably blow up when"
print "it goes off."
return 'death'

elif action == "slowly place the bomb":
print "You point you blaster at the bomb under your arm"
print "and the Gothons put their hands up and startto sweat."
print "You inch backward to the door, open it, and then carefully"
print "place the bomb on the floor, pointing your blaster at it."
print "You then jump back through the door, punch the close button"
print "and blast the lock so the Gothons can't get out."
print "Now that the bomb is placed you run to the escape pod to"
print "get off this tin can."
return 'escape_pod'
else:
print "DOES NOT COMPUTE!"
return "the_bridge"

def escape_pod(self):
print "You rush through the ship desperately trying to make it to"
print "the escape pod before the whole ship explodes. It seems like"
print "hardly any Gothons are on the ship, so your run is clear of"
print "interference. You get to the chamber with the escape pods, and"
print "now need to pick one to take. Some of them could be damaged"
print "but you don't have time to look. There's 5 pods while one"
print "do you take?"
good_pod = randint(1,5)
guess = raw_input("[pod #]> ")

if int (guess) != good_pod:
print "You jump into pod %s and hit the eject button." % guess
print "The pod escapes out into the void of space, then"
print "implodes as the hull ruptures, crushing your body"
print "into jam jelly."
return 'death'
else:
print "You jump into pod %s and hit the eject button." % guess
print "The pod easily slides out into space heading to"
print "the planet below. As it flies to the planet, you look"
print "back and see your ship implode then explode like a"
print "bright star, taking out the Gothon ship at the same"
print "time. You won!"
exit(0)

a_game = Game('central_corridor')
a_game.play()


(1)有关于getattr的用法

pydoc getattr,里面写着getattr(x, ‘y’)就相当于x.y,比如room = getattr(self, ‘central_corridor’)就相当于room = self.central_corridor,就是把函数当作变量赋值给room,然后next = room()就是调用函数

实例如下:

# coding:utf-8
class Test(object):
a = 10

def __init__(self):
pass
def test_getattr(self):
self.d=10
b = 20
return self.d

if __name__ == '__main__':
t = Test()

result_1 = getattr(t,'test_getattr','NO_Method') # 获取对象t中的'test_getattr'的方法,存在就打印出方法的内存地址。
result_2 = getattr(t,'a','default') # 获取对象t中的a变量,若没有,则返回default
result_3 = getattr(t,'c','default') # 获取对象t中的c变量,若没有,则返回default
result_4 = getattr(t,'test_getattr')() # 获取对象t中的test_getattr方法,后面加括号可以将这个方法运行。

print 'result_1=', result_1
print 'result_2=', result_2
print 'result_3=', result_3
print 'result_4=', result_4


运行结果:



加分习题

1. 研究一下 dict 是什么东西,应该怎样使用。

python中class的dict包含了类的属性

class A():
def __init__(self):
self.x=1   #定义一个实例属性
y = 2          #定义一个类属性

a = A()
print a.__dict__
print a.y
print a.x
a.__dict__ = {} #清空实例的所有属性,y不受影响,因为他是类属性而非实例属性
print a.__dict__
print a.y
print a.x #这里会提示不包含x属性的错误,因为已被清空
print A.__dict__
A.__dict__ = {} #清空类的所有属性,x不受影响
print a.x
print a.y #提示错误


再为游戏添加一些房间,确认自己已经学会使用 class 。

添加代码:

class A(object):
def __init__(self,ccc):
self.c = [
"It's a good day!",
"Let's play football.",
"And how do you do?"
]
self.ccc = ccc

def test(self):
next = self.ccc
print next
print self.c[1]

a = A("just a
10c7a
test project:")
a.test()


执行结果:

pony@pony-PC:/media/pony/文档/pythonex$ python ex42b.py
just a test project:
Let's play football.

------
The Gothons of Planet Per cal #25 have invaded your ship and destroyed
your entire crew. You are the last surviving member and your last
mission is to get the neutron destruct bomb from the Weapons Armory,
put it in the bridge, and blow the ship up after getting into an
escape pod.

You're running down the central corridor to the Weapons Armory when
a Gothonsjumps out, red scaly skin, dark grimy teeth, and evil clown costume
flowing around his hate filled body. He's blocking the door to the
Armory and about to pull a weapon to blast you.
> dodge!
Like a world class boxer you dodge, weave, slip and slip right
as the Gothon's blaster cranks a laser past your head.
In the middle of your artful dodge your foot slips and you
bang your head on the metal wall and pass out.
You wake up shortly after only to die as the Gothon stomps on
your head and eats you.

------
I have a small puppy that's better at this.


创建一个新版本,里边使用两个 class,其中一个是 Map ,另一个是 Engine 。提示: 把 play 放到 Engine 里面。

代码:

from sys import exit
from random import randint

class Map(object):
def __init__(self):
self.quips = [
"You died. You kinda suck at this.",
"Your mom would be pround. If she were smater.",
"Such a luser.",
"I have a small puppy that's better at this."
]

def death(self):
print self.quips[randint(0,len(self.quips) - 1)]
exit(1)

def central_corridor(self):
print "The Gothons of Planet Per cal #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 from the Weapons Armory,"
print "put it in the bridge, and blow the ship up sfter getting into an"
print "escape pod."
print "\n"
print "You're running down the central corridor too the Weapons Armory when"
print "a Gothon jumps out, red scaly skin, dark grimy teeth, and evil clown custom"
print "flowing around his hate filled body.He's blocking the door to the "
print "Aromry 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 cosume 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 ship right"
print "as the Gothon's blaster cranks a laser past your head."
print "In the middle of your atrful dodge your foot slips aand 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 square in the head"
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 Goothons that might be hiding. It's fead 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 "wrooong 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 != code and guesses < 10:
print "BZZZZEDDD!"
guesses += 1
guess = raw_input("[keypad]> ")

if guess == code:
print "The container clicks open and the seal breaks, letting gas out."
print "You grab the neutron bomb and run as fast as you can to the"
print "bridge where you must place it in the right spot."
return 'the_bridge'

else:
print "The lock buzzes one last time and then you hear a sickening"
print "melting sound as the mechanism is fused together."
print "You decide to sit there, and finally the Gothons blow up the"
print "ship from their ship and you die."
return 'death'

def the_bridge(self):
print "You burst onto Bridge with the netron destruct bomb"
print "under your arm and surprise 55 Gothons who sre trying to"
print "take control of the ship. Each of them has an even uglier"
print "clown costume than the last. They haven't pulled their"
print "arm and don't want to set it off."

action = raw_input("> ")

if action == "throw the bomb":
print "In a panic you throw the bomb at the group of Gothons"
print "and make a leap for the door. Right as you drop it a"
print "Gothon shoots you right in the back killing you."
print "As you die you see anothor Gothon frantically try to disarm"
print "the bomb. You die knowing they will probably blow up when"
print "it goes off."
return 'death'

elif action == "slowly place the bomb":
print "You point you blaster at the bomb under your arm"
print "and the Gothons put their hands up and startto sweat."
print "You inch backward to the door, open it, and then carefully"
print "place the bomb on the floor, pointing your blaster at it."
print "You then jump back through the door, punch the close button"
print "and blast the lock so the Gothons can't get out."
print "Now that the bomb is placed you run to the escape pod to"
print "get off this tin can."
return 'escape_pod'
else:
print "DOES NOT COMPUTE!"
return "the_bridge"

def escape_pod(self):
print "You rush through the ship desperately trying to make it to"
print "the escape pod before the whole ship explodes. It seems like"
print "hardly any Gothons are on the ship, so your run is clear of"
print "interference. You get to the chamber with the escape pods, and"
print "now need to pick one to take. Some of them could be damaged"
print "but you don't have time to look. There's 5 pods while one"
print "do you take?"
good_pod = randint(1,5)
guess = raw_input("[pod #]> ")

if int (guess) != good_pod:
print "You jump into pod %s and hit the eject button." % guess
print "The pod escapes out into the void of space, then"
print "implodes as the hull ruptures, crushing your body"
print "into jam jelly."
return 'death'
else:
print "You jump into pod %s and hit the eject button." % guess
print "The pod easily slides out into space heading to"
print "the planet below. As it flies to the planet, you look"
print "back and see your ship implode then explode like a"
print "bright star, taking out the Gothon ship at the same"
print "time. You won!"
exit(0)

class Engine(object):
def __init__(self,a):
self.b = Map()
self.a = a

def play(self):
next = self.a
while True:
print "\n--------"
room = getattr(self.b, next)
next = room()

a_engine=Engine("central_corridor")
a_engine.play()


笔记:

(1)定义Map()类别,将原来的Game()中除play()函数都放进来

(2)定义Engine()类别,通过b=Map()将Map()类别引入到Engine中来

(3)不一定非要用start,可以是任意的参数,都能够传递到Engine类别中

贴一下我在做这一题中出现的几个错误:

(1)

pony@pony-PC:/media/pony/文档/pythonex$ python ex42c.py
Traceback (most recent call last):
File "ex42c.py", line 160, in <module>
a_engine=Engine("central_corridor")
File "ex42c.py", line 150, in __init__
self.map=Map()
TypeError: __init__() takes exactly 2 arguments (1 given)


这个错误的意思是init需要两个参数,但是你只给出了一个参数。检查后发现,我把第一个类别Map()中引用了参数start,具体错误代码为:

def __init__(self,start):
self.quips = [
"You died. You kinda suck at this.",
"Your mom would be pround. If she were smater.",
"Such a luser.",
"I have a small puppy that's better at this."
]
self.start = start


删除Map()中start相关的代码即可。

(2)

pony@pony-PC:/media/pony/文档/pythonex$ python fj29.py
File "fj29.py", line 17
def central_corridor(self):
^
IndentationError: unindent does not match any outer indentation level


这个代码的意思是缩进出现了问题,检查是否用空格代替了tab导致的。具体的可以参考:https://www.crifan.com/python_syntax_error_indentationerror/comment-page-1/

(3)

pony@pony-PC:/media/pony/文档/pythonex$ python ex42c.py

--------
The Gothons of Planet Per cal #25 have invaded your ship and destroyed.
your entire crew. You are the last surviving member and your last
mission is to get the neutron destruct bomb from from the Weapons Armory,
put it in the bridge, and blow the ship up sfter getting into an
escape pod.

You're running down the central corridor too the Weapons Armory when
a Gothon jumps out, red scaly skin, dark grimy teeth, and evil clown custom
flowing around his hate filled body.He's blocking the door to the
Aromry and about to pull a weapon to blast you.
> dodge!
Like a world class boxer you dodge, weave, slip and ship right
as the Gothon's blaster cranks a laser past your head.
In the middle of your atrful dodge your foot slips aand you
bang your head on the metal wall and pass out.
You wake up shortly after only to die as the Gothon stomps on
your head and eats you.

--------
You died. You kinda suck at this.

--------
Traceback (most recent call last):
File "ex42c.py", line 163, in <module>
a_engine.play()
File "ex42c.py", line 159, in play
room = getattr(self.map, next)
TypeError: getattr(): attribute name must be string


这个问题是由于getattr 第二个参数必须为 str,而代码里面 next = room() 应该是这个 room 返回了一个非 str 的东西。

在Map()类别中的death()的末尾添加exit(1)即可。

本节课涉及的知识(引用自网友,仅作为个人笔记使用)

①from sys import exit 从sys模组中引入exit即退出功能

Python退出程序的方式有两种:os._exit(), sys.exit()

1)os._exit() 直接退出 Python程序,其后的代码也不会继续执行。

2)sys.exit() 引发一个 SystemExit异常,若没有捕获这个异常,Python解释器会直接退出;捕获这个异常可以做一些额外的清理工作。0为正常退出,其他数值(1-127)为不正常,可抛异常事件供捕获。

exit() 跟 C 语言等其他语言的 exit() 应该是一样的。

os._exit() 调用 C 语言的 _exit() 函数。

一般来说os._exit() 用于在线程中退出

sys.exit() 用于在主线程中退出。

②from random import randint 从random模组中引入randint即产生随机整型数

Python中的random模块用于生成随机数。下面介绍一下random模块中最常用的几个函数。

random.random

random.random()用于生成一个0到1的随机符点数: 0 <= n < 1.0

random.uniform

random.uniform的函数原型为:random.uniform(a, b),用于生成一个指定范围内的随机浮点数,两个参数其中一个是上限,一个是下限。如果a > b,则生成的随机数n: a <= n <= b。如果 a < b, 则 b <= n <= a。

random.randint

random.randint()的函数原型为:random.randint(a, b),用于生成一个指定范围内的整数。其中参数a是下限,参数b是上限,生成的随机数n: a <= n <= b

printrandom.randint(20,10)#该语句是错误的。下限必须小于上限。

random.randrange

random.randrange的函数原型为:random.randrange([start], stop[, step]),从指定范围内,按指定基数递增的集合中 获取一个随机数。如:random.randrange(10, 100, 2),结果相当于从[10, 12, 14, 16, … 96, 98]序列中获取一个随机数。random.randrange(10, 100, 2)在结果上与 random.choice(range(10, 100, 2) 等效。

random.choice

random.choice从序列中获取一个随机元素。其函数原型为:random.choice(sequence)。参数sequence表示一个有序类型。这里要说明一下:sequence在python不是一种特定的类型,而是泛指一系列的类型。list, tuple, 字符串都属于sequence。有关sequence可以查看python手册数据模型这一章。下面是使用choice的一些例子:

random.shuffle

 random.shuffle的函数原型为:random.shuffle(x[, random]),用于将一个列表中的元素打乱。如:p=[“Python”,”is”,”powerful”,”simple”,”andsoon…”]

random.shuffle(p)

print p

1

2

random.sample

random.sample的函数原型为:random.sample(sequence, k),从指定序列中随机获取指定长度的片断。sample函数不会修改原有序列。

如:list=[1,2,3,4,5,6,7,8,9,10]

slice=random.sample(list,5)#从list中随机获取5个元素,作为一个片断返回到slice
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 笔记