ex42

对象分为类对象和实例对象。类对象是用class命名时就生成了一个类对象;实例对象简称对象,是当实例化时生成的对象。

## Animal is-a object
class Animal(object):def __init__(self):self.legs = 4self.tail = 1       ## Dog is-a Animal
class Dog(Animal):def __init__(self, name):## Dog has-a nameself.name = nameself.sound = "Wangwang"self.food = "Dog food"def love(self):self.love = "Chase cat"## Cat is-a Animal
class Cat(Animal):def __init__(self, name):## Cat has-a nameself.name = nameself.sound = "Miao miao"self.food = "fish"def love(self):self.love = "eat fish"## Person is-a object
class Person(object):def __init__(self, name):## Person has-a nameself.name = name## Person has-a pet of some kindself.pet = Noneself.fish = None## Employee is-a Person
class Employee(Person):def __init__(self, name, salary):##  Employee has-a namesuper(Employee,self).__init__(name)## Employee has-a salaryself.salary = salary## Fish is-a object
class Fish(object):def __init__(self,name):self.name = nameself.tail = 1self.eye =2## Salmon is-a Fish
class Salmon(Fish):def __init__(self,name):super(Salmon, self).__init__(name)## Halibut is-a Fish
class Halibut(Fish):def __init__(self,name):super(Halibut, self).__init__(name)## rover is-a Dog
rover = Dog("Rover")## satan is-a Cat
satan = Cat("Satan")
tom = Cat("Tom")## mary is-a Person
mary = Person("Mary")
joy = Person("Tom")## mary.pet has-a satan
mary.pet = satan
joy.pet = tom## frank is-a Emplyee
frank = Employee("Frank", 120000)
mary = Employee("Mary", 120)
joy = Employee("Joy", 80)## frank.pet has-a rover
frank.pet = rover## flipper is-a Fish
flipper = Fish("Flipper")## crouse is-a Salmon
crouse = Salmon("Crouse")## harry is-a Haibut()
harry = Halibut("harry")print(f"{mary.name} 's salary is {mary.salary}. She has a cat {satan.name}, which love eat {crouse.tail} Salmon. ")if mary.salary < frank.salary:print(f"{mary.name} was poor, {frank.name}'s dog {rover.name} was full.")
else:print(f"{mary.name} was rich, {frank.name}'s dog {rover.name} was hungry.")

ex43

面向对象的程序怎么写

  1. 把问题写出来或画出来。

  2. 从1中提炼出关键概念,并研究它们。列出名词清单和动词清单。

  3. 为概念创建类树和对象地图。梳理名词之间的层次关系,建立类树;动词作为函数,看放入类树下的哪个类里合适。

  4. 为类写程序,并测试它们。先写框架,也就是只有类名字和函数名字,写代码的地方用pass占位置;然后不断写一段小代码,不断测试,直到完成。

  5. 不断重复和改善。如果遇到难题,就专心攻克它。

# 因为要设置离开,所以要exit
# 因为要猜密码,而密码是随机数字,所以要randint
# 因为要对文本进行处理,移去空格前缀,所以要dedent
from sys import exit
from random import randint
from textwrap import dedent# Scene只是一个简单说明。
class Scene(object):def enter(self):print("This scene is not yet configured.")print("Subclass it and implement enter().")exit(1)# Engine
# 输入:当前场景
# 输出:如果当前场景不是最后场景,则根据当前场景的结果转换为下一个场景;
#      如果当前场景是最后场景,则进入最后场景。
class Engine(object):def __init__(self,scene_map):self.scene_map = scene_mapdef play(self):current_scene = self.scene_map.opening_scene()last_scene = self.scene_map.next_scene('finished')while current_scene != last_scene:next_scene_name = current_scene.enter()current_scene = self.scene_map.next_scene(next_scene_name)# be sure to print out the last scenecurrent_scene.enter()# Death的输出:从嘲弄列表中随意挑出一种死法。
class Death(Scene):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.","You're worse than your Dad's jokes."]def enter(self):print(Death.quips[randint(0, len(self.quips)-1)])        exit(1)class CentralCorridor(Scene):def enter(self):print(dedent("""The Gothons of Planet Percal #25 have invaded your ship anddestroyed your entire crew. You are the last survivingmember and your last mission is to get the neutron destructbomb from the Weapons Armory, put it in the bridge, andblow the ship up after getting into an escape pod.You're running down the central corridor to the WeaponsArmory when a Gothon jumps out, red scaly skin, dark grimyteeth, and evil clown costume flowing around his hatefilled body. He's blocking the door to the Armory andabout to pull a weapon to blast you. """))action = input("> ")if action == "shoot!":print(dedent("""Quick on the draw you yank out your blaster and fireit at the Gothon. His clown costume is flowing andmoving around his body, which throws off your aim.Your laser hits his costume but misses him entirely.This completely ruins his brand new costume his motherbought him, which makes him fly into an insane rageand blast you repeatedly in the face until you aredead. Then he eats you.             """))return 'death'elif action == "dodge!":print(dedent("""Like a world class boxer you dodge, weave, slip andslide right as the Gothon's blaster cranks a laserpast your head. In the middle of your artful dodgeyour foot slips and you bang your head on the metalwall and pass out. You wake up shortly after only todie as the Gothon stomps on your head and eats you."""))return 'death'elif action == 'tell a joke':print(dedent("""Lucky for you they made you learn Gothon insults inthe academy. You tell the one Gothon joke you know:Lbhe zbgure vf fb sng, jura fur fvgf nebhaq gur ubhfr,fur fvgf nebhaq gur ubhfr. The Gothon stops, triesnot to laugh, then busts out laughing and can't move.While he's laughing you run up and shoot him square inthe head putting him down, then jump through theWeapon Armory door.            """))return 'laser_weapon_armory'else:print('DOES NOT COMPUTE!')return 'central_corridor'class LaserWeaponArmory(Scene):def enter(self):print(dedent("""You do a dive roll into the Weapon Armory, crouch and scanthe room for more Gothons that might be hiding. It's deadquiet, too quiet. You stand up and run to the far side ofthe room and find the neutron bomb in its container.There's a keypad lock on the box and you need the code toget the bomb out. If you get the code wrong 10 times thenthe lock closes forever and you can't get the bomb. Thecode is 3 digits."""))# code = f"{randint(1,9)}{randint(1,9)}{randint(1,9)}"code = "111"guess = input("[keypad]> ")guesses = 0while guess != code and guesses < 10:print("BZZZZEDDD!")guesses += 1guess = input("[keypad]> ")if guess == code:print(dedent("""The container clicks open and the seal breaks, lettinggas out. You grab the neutron bomb and run as fast asyou can to the bridge where you must place it in theright spot."""))return 'the_bridge'else:print(dedent("""The lock buzzes one last time and then you hear asickening melting sound as the mechanism is fusedtogether. You decide to sit there, and finally theGothons blow up the ship from their ship and you die."""))return 'death'class TheBridge(Scene):def enter(self):print(dedent("""You burst onto the Bridge with the netron destruct bombunder your arm and surprise 5 Gothons who are trying totake control of the ship. Each of them has an even uglierclown costume than the last. They haven't pulled theirweapons out yet, as they see the active bomb under yourarm and don't want to set it off."""))action = input("> ")if action == "throw the bomb":print(dedent("""In a panic you throw the bomb at the group of Gothonsand make a leap for the door. Right as you drop it aGothon shoots you right in the back killing you. Asyou die you see another Gothon frantically try todisarm the bomb. You die knowing they will probablyblow up when it goes off."""))return 'death'elif action == 'slowly place the bomb':print(dedent("""You point your blaster at the bomb under your arm andthe Gothons put their hands up and start to sweat.You inch backward to the door, open it, and thencarefully place the bomb on the floor, pointing yourblaster at it. You then jump back through the door,punch the close button and blast the lock so theGothons can't get out. Now that the bomb is placedyou run to the escape pod to get off this tin can."""))return 'escape_pod'else:print("DOES NOT COMPUTE!")return "the_bridge"class EscapePod(Scene):def enter(self):print(dedent("""You rush through the ship desperately trying to make itthe escape pod before the whole ship explodes. It seemslike hardly any Gothons are on the ship, so your run isclear of interference. You get to the chamber with theescape pods, and now need to pick one to take. Some ofthem could be damaged but you don't have time to look.There's 5 pods, which one do you take?"""))# good_pod = randint(1, 5)good_pod = 1guess = input("[pod #]> ")if int(guess) != good_pod:print(dedent(f"""You jump into pod {guess} and hit the eject button.The pod escapes out into the void of space, thenimplodes as the hull ruptures, crushing your body intojam jelly."""))return 'death'else:print(dedent(f"""You jump into pod {guess} and hit the eject button.The pod easily slides out into space heading to theplanet below. As it flies to the planet, you lookback and see your ship implode then explode like abright star, taking out the Gothon ship at the sametime. You won!            """))return 'finished'class Finished(Scene):def enter(self):print("You won! Good job.")return 'finished'# 地图的输入:一个变量
# 输出:变量的值,也即是各个场景的类。class Map(object):scenes = {'central_corridor': CentralCorridor(),'laser_weapon_armory': LaserWeaponArmory(),'the_bridge': TheBridge(),'escape_pod': EscapePod(),'death': Death(),'finished':Finished()}def __init__(self, start_scene):self.start_scene = start_scenedef next_scene(self, scene_name):val = Map.scenes.get(scene_name)return valdef opening_scene(self):return self.next_scene(self.start_scene)a_map = Map('central_corridor')
a_game = Engine(a_map)  # 将对象作为参数,进入类Engine。
a_game.play()

《Learn python3 the hard way》ex42到ex43总结相关推荐

  1. 解析learn the python3 the hard way里的ex43

    earn the python3 the hard way里的ex43难度陡增,因为代码超过百行,里面的文字又太多,但是有不少有趣的小套路,大家也可以试着总结一下. from sys import e ...

  2. 练习《learn Python3 the hard way》(Zed Shaw)ex25无法导入模块

    <learn Python3 the hard way>(Zed Shaw)ex25中需要import ex25,但是在cmd里,python编译器里都无法运行. 只能在powershel ...

  3. 《Learn python3 the hard way》ex14 Prompting and Passing

    今天是使用提示语>以及运用argv 和 input进行交互. from sys import argvscript, user_name = argv prompt = ">&q ...

  4. 《Learn python3 the hard way》ex20函数和文件

    1-seek(0)用于重置指针到文件开头的位置,重新开始 因为在打印完全文时光标已至文尾,要重新打印一行一行需要光标回到开头. 2-readline()是按行来读文件,所以每次打印时只打印一行. fr ...

  5. 笨方法学python3: ex43中文魔改

    181007:把 Learn Python3 The Hard Way 一书的第43道练习题改成中文版.此外,刻意调低了难度.(话说中文书名翻成<用心学python>不可以么?) 这个游戏 ...

  6. python3视频教程-Python3深度学习视频学习路线

    (关注'AI新视野'公众号,发送"资料'二字,免费获取50G人工智能视频教程!) 经常有粉丝问我:"什么都不懂,怎么入门深度学习?".确实,对于初学者来说,网上繁多的教程 ...

  7. python3笔记_Python3学习笔记(四)

    原标题:Python3学习笔记(四) 错误.调试和测试 程序运行中,可能会遇到BUG.用户输入异常数据以及其它环境的异常,这些都需要程序猿进行处理.Python提供了一套内置的异常处理机制,供程序猿使 ...

  8. python 修改计算机名_静心学数据分析002-python基础

    1.前言 在安装好miniconda后,可以开始<learn python3 the hard way--a very simple introduction to the terrifying ...

  9. radiant序列码_阅“码”无数|第一期

    在前面的话 大家好,这里是你们的神雕.这是阅"码"无数系列的第一期,同时也是我博客CPL系列的第82期.公众号主要分享资源简要介绍.供大家快速了解相关感兴趣资源,对应的资源链接请戳 ...

最新文章

  1. 蚂蚁金服-支付风险识别亚军方案!
  2. sh256sum、xxd、base64联合计算文件的hash
  3. batchsize一定是2的幂_支付接口的幂等性设计
  4. Mybatis学习第一天——Mybatis的安装配置以及基本CURD操作
  5. telnet服务器显示本机,记一次困扰了我一个月的服务器telnet故障是如何解决的?...
  6. springboot项目和云服务器,以及域名的申请和使用(后续持续更新)
  7. Archlive新年第一棒: 基于2.6.37稳定内核的archlive20110107
  8. 保姆级My SQL-5.7.19安装教程
  9. 求1 2 3 java_求1+2+3+...+n,Java代码实现
  10. react 动态添加组件属性_React的组件动态参数使用Underscore和Context来传递
  11. HTML DOM学习
  12. 软件基本功:数组赋值,一定要对齐
  13. python中string函数的用法_python中string模块各属性以及函数的用法
  14. 前后端分离的微信小程序--校园二手交易平台
  15. 学习单片机开发——浅尝点灯的快乐
  16. linux查看udp端口占用命令,详解Linux查看端口占用
  17. android手机双开微信方法,微信双开太简单了!学会这几种方法,就能同时登录2个微信...
  18. Unity笔记-29-ARPG游戏项目-13-打击感(卡肉)与僵直感
  19. 工具类产品适合在微信公众号上运营吗?
  20. mysql (1205, 'Lock wait timeout exceeded; try restarting transaction')

热门文章

  1. xampp 403 禁止访问 问题解决
  2. Codeforces Problem-1593A Elections
  3. 顺序查找 题目编号:517
  4. win10 使用多桌面的两种方式
  5. zigbee设备入网流程分析
  6. h5调取摄像头实时显示并点击按钮拍照
  7. 金融业务架构的技术挑战
  8. Linux系统日志管理
  9. iPhone内存比Android手机小,iPhone内存为什么一直这么小
  10. c语言实现rsa签名验证,C语言openssl库RSA签名