PythonThinking_T7 OOP

T7面向对象编程
本文小结:
1.本文主要参考《Python从入门到实践》《Learn-Python-3-the-Hard-Way》,将有关OPP的练习都跑了一遍
2.联想到java,OPP的三大特性:封装、继承、多态,
https://blog.csdn.net/jianyuerensheng/article/details/51602015
查阅了Python相关特性:
封装
https://www.cnblogs.com/Michael–chen/p/6740455.html
继承与多态
https://www.liaoxuefeng.com/wiki/1016959663602400/1017497232674368
3.查阅了优秀作业,发现我的内容还行,但排版有待改进,空闲时间可以学一学

————
目录:
《Python从入门到实践》第9章 类  138
9.1 创建和使用类  138
9.1.1 创建Dog类  139
9.1.2 根据类创建实例  140
9.2 使用类和实例  142
9.2.1 Car类  143
9.2.2 给属性指定默认值  143
9.2.3 修改属性的值  144
9.3 继承  147
9.3.1 子类的方法__init__()  147
9.3.2 Python 2.7中的继承  149
9.3.3 给子类定义属性和方法  149
9.3.4 重写父类的方法  150
9.3.5 将实例用作属性  150
9.3.6 模拟实物  152
9.4 导入类  153
《Learn-Python-3-the-Hard-Way》

习题40 模块、类和对象 125
模块和字典差不多 125
1 mystuff[‘apple’] # get apple from dict
2 mystuff.apple() # get apple from the module
3 mystuff.tangerine # same thing, it’s just a variable
类和模块差不多 126
对象和import差不多 127
获取某样东西里包含的东西 128
第 一个类的例子 128
应该看到的结果 129
巩固练习 129
常见问题回答 130

习题41 学习面向对象术语 131
专有词汇练习 131
措辞练习 131
混合巩固练习 132
阅读测试 132
练习从语言到代码 134
阅读更多代码 135
常见问题回答 135
习题42 对象、类及从属关系 136
代码写成什么样子 137
关于class Name(object) 139
巩固练习 139
常见问题回答 139
习题43 基本的面向对象分析和设计 141
简单游戏引擎的分析 142
自顶向下与自底向上 146
《来自Percal 25号行星的哥顿人》
的代码 146
应该看到的结果 153
巩固练习 153
常见问题回答 154
习题44 继承与组合 155
什么是继承 155
要用super()的原因 160
组合 160
继承和组合的应用场合 162
巩固练习 162
常见问题回答 162
Test:
————
总结名词:
实例、属性等

词汇训练:
class:tell python to make a new type of thing
object
instance:what you get when you tell py to creat a class
def:
self:

短语训练:
class X(Y):make a class named X that is-a Y


#test
class Dog():
    def __init__(self,name,age):
        self.name=name
        self.age=age
    def sit(self):
        print(self.name,"is sitting now.")

my_dog=Dog('puppy',1)
my_dog.sit()
class Hair(Puppy):
    def __init__(self,hair="yellow"):
        self.hair=hair
    def describe_hair(self):
        print("puppy have a",self.hair,"hair")
#继承
class Puppy(Dog):
    def __init__(self,name,age):
        super().__init__(name,age)
        #composition
        self.hair=Hair()
        #每次初始化都实例化Hair(),并保存在self.hair里
    #override
    def sit(self):
        print("son is sitting now")
    
    
my_puppy=Puppy('wangwang',2)
my_puppy.sit()
my_puppy.hair.describe_hair()
puppy is sitting now.
son is sitting now
puppy have a yellow hair
#PY_HDW 41
# 总结:
# class Tell Python to make a new type of thing.
# object Two meanings: the most basic type of thing, and any instance of some thing.
# instance What you get when you tell Python to create a class.
# def How you define a function inside a class.
# self Inside the functions in a class, self is a variable for the instance/object being accessed.
# inheritance The concept that one class can inherit traits from another class, much like you and your parents.
# composition The concept that a class can be composed of other classes as parts, much like how a car has wheels.
# attribute A property classes have that are from composition and are usually variables.
# is-a A phrase to say that something inherits from another, as in a “salmon” is-a “fish.”
# has-a A phrase to say that something is composed of other things or has a trait, as in “a salmon has-a mouth.”

# classX(Y) “Make a class named X that is-a Y.”
# classX(object):def__init__(self,J) “class X has-a __init__ that takes self and J parameters.”
# classX(object):defM(self,J) “class X has-a function named M that takes self and J parameters.”
# foo=X() “Set foo to an instance of class X.”
# foo.M(J) “From foo, get the M function, and call it with parameters self, J.”
# foo.K=Q “From foo, get the K attribute, and set it to Q.”

import random
from urllib.request import urlopen
import sys

WORD_URL = "http://learncodethehardway.org/words.txt"
WORDS = []

PHRASES = {
	"class %%%(%%%)":"Make a class named %%% that is-a %%%",
	"class %%%(object):\n\tdef __init__(self, ***)":
	"class %%% has-a __init__ that takes self and *** params.",
	"class %%%(object):\n\tdef ***(self, @@@)":
	"class %%% has-a function *** that takes self and @@@ params.",
	"*** = %%%()":
	"Set *** to an instance of class %%%.",
	"***.***(@@@)":
	"From *** get the *** function, call it with params self, @@@.",
	"***.*** = '***'":
	"From *** get the *** attribute and set it to '***'."
	}

#do they want to dill phrases first
if len(sys.argv) == 2 and sys.argv[1] == "English":
	PHRASE_FIRST = True
else:
	PHRASE_FIRST = False

# load up the words from the website
for word in urlopen(WORD_URL).readlines():
	WORDS.append(str(word.strip(), encoding='utf-8'))

def convert(snippet, phrase):
	class_names = [w.capitalize() for w in random.sample(WORDS, snippet.count("%%%"))]
	other_names = random.sample(WORDS, snippet.count("***"))
	results = []
	param_names = []

	for i in range(0, snippet.count("@@@")):
		param_count = random.randint(1,3)
		param_names.append(', '.join(random.sample(WORDS, param_count)))

	for sentence in snippet, phrase:
		result = sentence[:]

		# fake class names
		for word in class_names:
			result = result.replace("%%%", word, 1)

		#fake  other names
		for word in other_names:
			result = result.replace("***", word, 1)

		# fake paramether lists
		for word in param_names:
			result = result.replace("@@@", word, 1)

		results.append(result)

	return results


# keep goning until the hit CTRL-D

try:
	while True:
		snippets = list(PHRASES.keys())
		random.shuffle(snippets)

		for snippet in snippets:
			phrase = PHRASES[snippet]
			question, answer = convert(snippet, phrase)
			if PHRASE_FIRST:
				question, answer = answer, question

			print(question)

			input(">")
			print(f"ANSWER: {answer}\n\n")

except EOFError:
	print("\nBye")
class Driving(object):
	def advertisement(self, cow, door, doll)
>1
ANSWER: class Driving has-a function advertisement that takes self and cow, door, doll params.


class Can(object):
	def __init__(self, cast)
>class Can has-a function __init__ that takes self and cast
ANSWER: class Can has-a __init__ that takes self and cast params.


animal = Decision()
>Set animal to an instance of class animal
ANSWER: Set animal to an instance of class Decision.


door.baseball(coal, balloon, creator)
>from door,get the baseball function, and call it with coal, ballon and creator 
ANSWER: From door get the baseball function, call it with params self, coal, balloon, creator.


dogs.committee = 'body'
>from dogs,get the committee attribute,and set it to body
ANSWER: From dogs get the committee attribute and set it to 'body'.


class Cloth(Branch)
>make a class named Cloth that is-a Branch
ANSWER: Make a class named Cloth that is-a Branch


chess.attack(chess, crow, arm)
>from,get function,and call it with
ANSWER: From chess get the attack function, call it with params self, chess, crow, arm.


burn.chalk = 'bait'
>1
ANSWER: From burn get the chalk attribute and set it to 'bait'.


class Company(object):
	def bedroom(self, dogs, bed)
# PYCC C9类
class Dog():
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def sit(self):
        print(self.name.title() + " is now sitting.")
    def roll_over(self):
        print(self.name.title()+" rolled over!")
# 实例化

my_dog = Dog('willie', 6)
print("my dog's name is" , my_dog.name.title())
print("My dog is",str(my_dog.age))
my_dog.roll_over()
my_dog.sit()

my dog's name is Willie
My dog is 6
Willie rolled over!
Willie is now sitting.
#9.2使用类和实例
    #给属性默认值
    #N:修改属性的值
class Car():
    def __init__(self,make,model,year):
        self.make=make
        self.model=model
        self.year=year
        self.odometer_reading=0#给属性默认值
    def get_descriptive_name(self):
        long_name=str(self.year),self.make,self.model
        return long_name
    def read_odometer(self):
        print("This car has ",str(self.odometer_reading))
    def update_odometer(self,mileage): #N:修改属性的值
        if mileage>=self.odometer_reading:
            self.odometer_reading=mileage
        else:
            print("you can't roll back an odometer")
my_car=Car('audi','a4',2016)
print(my_car.get_descriptive_name())
print(my_car.odometer_reading)
my_car.update_odometer(10)
print(my_car.odometer_reading)
my_car.update_odometer(5)
print(my_car.odometer_reading)
('2016', 'audi', 'a4')
0
10
you can't roll back an odometer
10
#每章节练习题有,没有答案,也可以尝试一下
#继承
class Car():
    def __init__(self,make,model,year):
        self.make=make
        self.model=model
        self.year=year
        self.odometer_reading=0
    def get_descriptive_name(self):
        long_name=str(self.year)+" "+self.make+" "+self.model
        return long_name
    def read_odometer(self):
        print("This car has ",str(self.odometer_reading))
    def update_odometer(self,mileage):
        if mileage>=self.odometer_reading:
            self.odometer_reading=mileage
        else:
            print("you can't roll back an odometer")
    def fill_gas_tank(self):
        print("The tank is fill.")
class ElectricCar(Car):#make a class that is-a Car
    def __init__(self,make,model,year):
        super().__init__(make,model,year)
#这行代码让Python调用ElectricCar 的父类的方法__init__() ,
#让ElectricCar 实例包含父类的所有属性。
#定义子类属性和方法:
        self.battery_size=70
    def describe_battery(self):
        print("This car has "+str(self.battery_size)+"-kwh battery.")
#重写父类的方法:
    def fill_gas_tank(self):
        print("This car does't need a gas tank.")
my_tesla=ElectricCar('tesla','model s',2016)
print(my_tesla.get_descriptive_name())
#定义子类属性和方法:
my_tesla.describe_battery()
#重写父类的方法:
my_car=Car('audi','A4',2016)
my_car.fill_gas_tank()
my_tesla.fill_gas_tank()
2016 tesla model s
This car has 70-kwh battery.
The tank is fill.
This car does't need a gas tank.
#9.3.5将实例用作属性
#组合? composition
class Car():
    def __init__(self,make,model,year):
        self.make=make
        self.model=model
        self.year=year
        self.odometer_reading=0
    def get_descriptive_name(self):
        long_name=str(self.year)+" "+self.make+" "+self.model
        return long_name
    def read_odometer(self):
        print("This car has ",str(self.odometer_reading))
    def update_odometer(self,mileage):
        if mileage>=self.odometer_reading:
            self.odometer_reading=mileage
        else:
            print("you can't roll back an odometer")
            
class ElectricCar(Car):
    def __init__(self,make,model,year):
        super().__init__(make,model,year)
        self.battery=Battery()
#这行代码让Python创建一个新的Battery 实例
#并将该实例存储在属性self.battery 中。
#每当方法__init__() 被调用时,都将执行该操作;
#因此现在每个ElectricCar 实例都包含一个自动创建的Battery 实例。
#另写一个类
    def test(self):
        self.battery.test()
class Battery():
    def __init__(self,battery_size=70):
        self.battery_size=battery_size
    def describe_battery(self):
        print("This car has "+str(self.battery_size)+"-kwh battery.")
    def test(self):
        print("This's compositopn")
my_tesla=ElectricCar('tesla','model s',2016)
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
my_tesla.test()
#直接使用类
my_battery=Battery(70)
my_battery.describe_battery()

2016 tesla model s
This car has 70-kwh battery.
This's compositopn
This car has 70-kwh battery.
#9.4导入类,因为这里没有保存文件名,所以已在Pycharm中完成
from car import Car, ElectricCar

my_beetle = Car('volkswagen', 'beetle', 2016)
  print(my_beetle.get_descriptive_name())

my_tesla = ElectricCar('tesla', 'roadster', 2016)
  print(my_tesla.get_descriptive_name())
#9.5 Python标准库
from collections import OrderedDict
#从collection模块导入OrdereDict类
favorite_languages = OrderedDict()
#实例化,调用OrderedDict() 来创建一个空的有序字典,
#并将其存储在favorite_languages 中
favorite_languages['jen'] = 'python'
favorite_languages['sarah'] = 'c'
favorite_languages['edward'] = 'ruby'
favorite_languages['phil'] = 'python'

for name, language in favorite_languages.items():
      print(name.title() + "'s favorite language is " +
          language.title() + ".")
#兼具列表和字典的主要优点(在将信息关联起来的同时保留原来的顺序)
Jen's favorite language is Python.
Sarah's favorite language is C.
Edward's favorite language is Ruby.
Phil's favorite language is Python.

《PY CC》本章小结:
我学会了如何编写类;如何使用属性在类中存储信息,以及如何编写方法,以让类具备所需的行为;
如何编写方法__init__() ,以便根据类创建包含所需属性的实例。你见识了如何修改实例的属性——包括直接修改以及通过方法进行修改。你还了解了:使用继承可简化相关类的创建工作;将一个类的实例用作另一个类的属性可让类更简洁。
通过将类存储在模块中,并在需要使用这些类的文件中导入它们,可让项目组织有序。你学习了Python标准库,并见识了一个使用模块collections 中的OrderedDict 类的示例。最后,你学习了编写类时应遵循的Python约定。

# practice
class Dog():
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def sit(self):
        print(self.name.title(), "is now sitting")

    def roll_over(self):
        print(self.name.title() + " rolled over!")


my_dog = Dog('puppy', 1)
my_dog.sit()
my_dog.roll_over()


# 组合composition
class Hair():
    def __init__(self, hair='yellow'):
        self.hair = hair

    def describe_hair(self):
        print("puppy hava a", self.hair, "hair")

# 继承
class Puppy(Dog):
    def __init__(self, name, age):
        super().__init__(name, age)
        self.hair = Hair()


my_puppy = Puppy('wangwang', 2)
my_puppy.sit()
my_puppy.hair.describe_hair()
Puppy is now sitting
Puppy rolled over!
Wangwang is now sitting
puppy hava a yellow hair
#HDW 40
#模块就像字典
mystuff = {'apple': "I AM APPLES!"}
print(mystuff['apple'])
I AM APPLES!
#is-a has-a
# Study Drills
#Whatdoes super(Employee, self).__init__(name) do?
# That’s how you can run the __init__method of aparent class reliably.Search for “python3.6super”and read the various advice on it being evil and good for you.

## Animal is-a object( (yes, sort of confusing) look at the extra credit )
class Animal(object):
	pass

## Dog is-a Animal;Dog has_a __init__ funtion that takes self and name para
class Dog(Animal):
	def __init__(self, name):
		super(Dog, self).__init__()
		self.name = name

##??
class Cat(Animal):
	def __init__(self, name):
		super(Cat, self).__init__()
		self.name = name

## ??
class Person(object):
	def __init__(self, name):
		##Person has-a name
		self.name = name
		##Person has-a pet of some kind
		self.pet = None

## ??

class Employee(Person):
	def __init__(self, name, salary):
		super(Employee, self).__init__(name)
		self.salary = salary

##??
class Fish(object):
	pass

##??
class Salmon(Fish):
	pass

##??
class Halibut(Fish):
	pass

## rover is a Dog
rover = Dog("Rover")

## ??
satan = Cat("Satan")

#??
mary = Person("Mary")

##??
mary.pet = santan

##??
frank = Employee("Frank", 120000)

##??
frank.pet = rover

##??
flipper = Fish()

##??
crouse = Salmon()

##??
harry = Halibut()


The Analysis of a Simple Game Engine
以一个游戏进行面向对象设计
1.Write or Draw About the Problem
2.Extract Key Concepts and Research Them
3.Create a Class Hierarchy and Object Map for the Concepts

#PY HDW 43
## Basic Obeject-Oritend Analysis and Design

# A TOP-DOWN process when you want to build something using python

# 1. Write or draw about the problem.
# 2. Extract key concepts from 1 and research them.
# 3. Create a class hierarchy and object map for the concepts.
# 4. Code the classes and a test to run them.
# 5. Repeat and refine.

# A BOTTOM-UP process
# Here are the general steps you follow to do this:
# 1. Take a small piece of the problem; hack on some code and get it to run barely.
# 2. Refine the code into something more formal with classes and automated tests.
# 3. Extract the key concepts you’re using and research them.
# 4. Write a description of what’s really going on.
# 5. Go back and refine the code, possibly throwing it out and starting over.
# 6. Repeat, moving on to some other piece of the problem.


#-------------------------------------
from sys import exit
from random import randint
from textwrap import dedent


class Scene(object):
	"""docstring for Scene"""
	def enter(self):
		print("This scene is not yet configured.")
		print("Subclass it and implement enter()")
		exit(1)

#???function:Map.opening_scene 和 Map.next_scene ,map里根本没有这样的方法
class Engine(object):
	"""docstring for Engine"""
	def __init__(self, scene_map):
		self.scene_map = scene_map

	def play(self):
		current_scene = self.scene_map.opening_scene()
        #from self(class or instance?),get the attribute? scene_map
		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 scene
			current_scene.enter()



class Death(Scene):
	"""docstring for Death"""

	quips = [
		"You died. You kinda suck at this.",
		"Your Mom would be proud...if she were smater.",
		"Such a luser.",
		"I have a small pyppy 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 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 pos.

			Your're running down the central corridor th the Weapons
			 Armory when aGothon jumps out, red scaly skin, dark grimy
			 teeth, and evil clown costume flowing around his hate
			 filled body. He's blocing the door to the Armory and
			 about to pull a weapon to blast you.
			 """))

		action = input(">")

		if action == "shoot!!":
			print(dedent("""
				Quick on draw you yank out your blaster and fire
				it at thhe Gothon. Hos clown costume is flowing and
				moving around his body, which throws of your aim.
				Your laser hits his costume but misses him entirely.
				This completely ruins his brand new costume his mother
				bought him, which makes him fly into an insane rage
				and blast you repeatedly in the face until you are
				dead. Then he eats you.
				"""))
			return "death"

		elif action == "dodge!":
			print(dedent("""
				Like a world class boxer you dodge, weave, slip and slide 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.
				"""))
			return "death"

		elif action == "tell a joke":
			print(dedent("""
				Lucky for you they made you learn Gothon insults in
				the academy. You tell the one Gothon joke you know:
				Lbhe zbgure vf fb sng, jura fur fvgf nebhaq gur ubhfr,
				not to laugh, then busts out laughing and can't move.
				While he's laughing you run up and shoot him square in
				the head putting him down, then jump through the
				Weapon 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 scan
				the room for more Gothons that might be hiding. It's dead
				quiet, too quiet. You stand up and run to the far side of
				the room and find the neutron bomb in its container.
				There's a keypad lock on the box and you need the code to
				get the bomb out. If you get the code wrong 10 times then
				the lock closes forever and you can't get the bomb. The
				code is 3 digits."""))

# 		code = f"{randint(1,9)}{randint(1,9)}{randint(1,9)}"
		code = f"{1} {2} {3}"
		guess = input("[keypad]> ")
		guesses = 0

		while guess != code and guesses < 10:
			print("BZZZZEDDD!")
			guesses += 1
			guess = input("[keypad]>")

		if guess == code:
			print(dedent("""
				The container clicks open and the seal breaks, letting
				gas out. You grab the neutron bomb and run as fast as
				you can to the bridge where you must place it in the
				right spot.
				"""))
			return 'the_bridge'
		else:
			print(dedent("""
				The lock buzzes one last time and then you hear a
				sickening melting sound as the mechanism is fused
				together. You decide to sit there, and finally the
				Gothons blow up the ship from their ship and you die.
				"""))
			return 'death'

class TheBrige(Scene):
	"""docstring for TheBrige"""
	def enter(self):
		print(dedent("""
		You burst onto the Bridge with the netron destruct bomb
		under your arm and surprise 5 Gothons who are trying to
		take control of the ship. Each of them has an even uglier
		clown costume than the last. They haven't pulled their
		weapons out yet, as they see the active bomb under your
		arm 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 Gothons
				and make a leap for the door Right as you drop it a
				Gothon shoots you right in the back killing you. As
				you die you see another Gothon frantically try to
				disarm the bomb. You die knowing they will probably
				blow 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 and
				the Gothons put their hands up and start to sweat.
				You inch backward to the door, open it, and then
				carefully place the bomb on the floor, pointing your
				blaster at it. You then jump back through the door,
				punch the close button and blast the lock so the
				Gothons can't get out. Now that the bomb is placed
				you 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):
	"""docstring for EscapePod"""

	def enter(self):
		print(dedent("""
			You rush through the ship desperately trying to make it to
			the escape pod before the whole ship explodes. It seems
			like hardly any Gothons are on the ship, so your run is
			clear of interference. You get to the chamber with the
			escape pods, and now need to pick one to take. Some of
			them 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 =1
		guess = input("[pod#]>")

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

			return 'finished'

class Finished(Scene):
	"""docstring for Finished"""

	def enter(self):
		print("You won! Good job.")
		return "finished"


class Map(object):
	"""docstring for Map"""


	scenes = {
	'central_corridor': CentralCorridor(),
	'laser_weapon_armory': LaserWeaponArmory(),
	'the_bridge': TheBrige(),
	'escape_pod': EscapePod(),
	'death': Death(),
	'finished': Finished()
		}
	def __init__(self, start_scene):
		super(Map, self).__init__()
		self.start_scene = start_scene

	def next_scene(slef, scene_name):
		val = Map.scenes.get(scene_name)
		#from class Map,get the function scenes.get,call it with scene_name,and set val
		return val
# get函数
# tinydict = {'Name': 'Runoob', 'Age': 27}
# print "Value : %s" %  tinydict.get('Age')
# print "Value : %s" %  tinydict.get('Sex', "Not Available")
# Value : 27
# Value : Not Available

	def opening_scene(self):
		return self.next_scene(self.start_scene)

if __name__ == '__main__':
	a_map = Map("central_corridor")
	a_game = Engine(a_map)
	a_game.play()
The Gothons of Planet Percal #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 pos.

Your're running down the central corridor th the Weapons
 Armory when aGothon jumps out, red scaly skin, dark grimy
 teeth, and evil clown costume flowing around his hate
 filled body. He's blocing the door to the Armory and
 about to pull a weapon to blast you.

>tell a joke

Lucky for you they made you learn Gothon insults in
the academy. You tell the one Gothon joke you know:
Lbhe zbgure vf fb sng, jura fur fvgf nebhaq gur ubhfr,
not to laugh, then busts out laughing and can't move.
While he's laughing you run up and shoot him square in
the head putting him down, then jump through the
Weapon Armory door.


You do a dive roll into the Weapon Armory, crouch and scan
the room for more Gothons that might be hiding. It's dead
quiet, too quiet. You stand up and run to the far side of
the room and find the neutron bomb in its container.
There's a keypad lock on the box and you need the code to
get the bomb out. If you get the code wrong 10 times then
the lock closes forever and you can't get the bomb. The
code is 3 digits.
[keypad]> 5 1 22
BZZZZEDDD!
[keypad]>1 2 3

The container clicks open and the seal breaks, letting
gas out. You grab the neutron bomb and run as fast as
you can to the bridge where you must place it in the
right spot.


You do a dive roll into the Weapon Armory, crouch and scan
the room for more Gothons that might be hiding. It's dead
quiet, too quiet. You stand up and run to the far side of
the room and find the neutron bomb in its container.
There's a keypad lock on the box and you need the code to
get the bomb out. If you get the code wrong 10 times then
the lock closes forever and you can't get the bomb. The
code is 3 digits.
[keypad]> 1 2 3

The container clicks open and the seal breaks, letting
gas out. You grab the neutron bomb and run as fast as
you can to the bridge where you must place it in the
right spot.


You burst onto the Bridge with the netron destruct bomb
under your arm and surprise 5 Gothons who are trying to
take control of the ship. Each of them has an even uglier
clown costume than the last. They haven't pulled their
weapons out yet, as they see the active bomb under your
arm and don't want to set it off.

>slowly place the bomb

You point your blaster at the bomb under your arm and
the Gothons put their hands up and start to sweat.
You inch backward to the door, open it, and then
carefully place the bomb on the floor, pointing your
blaster at it. You then jump back through the door,
punch the close button and blast the lock so the
Gothons can't get out. Now that the bomb is placed
you run to the escape pod to get off this tin can.


You burst onto the Bridge with the netron destruct bomb
under your arm and surprise 5 Gothons who are trying to
take control of the ship. Each of them has an even uglier
clown costume than the last. They haven't pulled their
weapons out yet, as they see the active bomb under your
arm and don't want to set it off.

>slowly place the bomb

You point your blaster at the bomb under your arm and
the Gothons put their hands up and start to sweat.
You inch backward to the door, open it, and then
carefully place the bomb on the floor, pointing your
blaster at it. You then jump back through the door,
punch the close button and blast the lock so the
Gothons can't get out. Now that the bomb is placed
you run to the escape pod to get off this tin can.


You rush through the ship desperately trying to make it to
the escape pod before the whole ship explodes. It seems
like hardly any Gothons are on the ship, so your run is
clear of interference. You get to the chamber with the
escape pods, and now need to pick one to take. Some of
them could be damaged but you don't have time to look.
There's 5 pods, which one do you take?

[pod#]>1

You jump into pod {guess} and hit the eject button.
The pod easily slides out into space heading to the
planet below. As it flies to the planet, you look
back and see your ship implode then explode like a
bright star, taking out the Gothon ship at the same
time. You won!


You rush through the ship desperately trying to make it to
the escape pod before the whole ship explodes. It seems
like hardly any Gothons are on the ship, so your run is
clear of interference. You get to the chamber with the
escape pods, and now need to pick one to take. Some of
them could be damaged but you don't have time to look.
There's 5 pods, which one do you take?

[pod#]>1

You jump into pod {guess} and hit the eject button.
The pod easily slides out into space heading to the
planet below. As it flies to the planet, you look
back and see your ship implode then explode like a
bright star, taking out the Gothon ship at the same
time. You won!

You won! Good job.

from sys import exit
from random import randint
from textwrap import dedent   
 
 
 
class Scene(object):
 
	def enter(self):
		print('This scene is not yet configured.')
		print('Subclass it and implement enter().')
		exit(1)
 
		
class Engine(object):
 
	def __init__(self, scene_map):
		self.scene_map = scene_map
	
	def 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 scene
		current_scene.enter()
 
		
class Death(Scene):
	
	quips = [
		"You died. You kinda suck at this.",
		"You 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 haveinvaded your ship and desteoyed 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 afther getiing into an escape pod.
			You're running down the central corridor to the Weapons Armory when a Gothon jumps out , 
			red scaly skin, dark grimy filled body.
			He's blocking the door to the Armory and about topull a weapon blast you.
		     """))
		
		action = input('> ')
		
		if action == "shoot!":
			print(dedent("""
				Quick on the draw you yank out your blaster and fire it at the Gothon. 
				His clown costume is flowing and moving around his body, which throws off you aim.
				This completely ruins his brand new costume but misses him entirely,
				which makes him fly into an insane rage and blast you repeatedly in the face untill you are dead.
				Then he eats you.
			     """))
			return 'death'
		
		elif action == 'dodge!':
			print(dedent("""
				Like a world class boxer you dodge, weave, slip and slide 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.
			     """))
			return 'death'
		
		elif action == 'tell a joke':
			print(dedent("""
				Lucky for you they made you learn Gothon insults in the academy. 
				You tell the one Gothon joke you know:
				Lbhe zbgure vf fb sng , jura fur fvgf nebhaq gur ubhfr, jura fur fvgf nebhaq gur ubhfr. 
				The Gothon stops, tries not to laugh, then busts out laughing and can't move.
				While he's laughing you run up and shoot him square in the head putting him down, then jump through the Weapon 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 scan the room for more Gothons that might be hiding. 
			It's dead quiet, too quiet. You stand up and run to the far side of the room and find the neutron bomb in its container.
			There's a keypad lock on the box and you need the code to get the bomb out. 
			If you get the code wrong 10 times then the lock closes forever and you can't get the bomb. 
			The code is 3 digits.
		     """))
		
		code = f"{1}{2}{3}"
		guess = input("[keypad]> ")
		guesses = 0
		
		while guess != code and guesses < 10:
			print('BZZZZEDDD!')
			guesses += 1
			guess = input("[keypad]> ")
			
		if guess == code:
			print(dedent("""
				The container clicks open and the seal breaks, letting gas out. 
				You grab the neutron bomb and run as fast as you can to he bridge where you must place it in the right spot.
			     """))
			return 'the_bridge'
		
		else:
			print(dedent("""
				The lock buzzes one last time and then you hear a sickening melting sound as the mechanism is fused together. 
				You decide to sit there, and you die.
			     """))
			return 'death'
			
 
class TheBridge(Scene):
	
	def enter(self):
		print(dedent("""
			You burst onto the Bridge with the netron destruct bomb under your arm and surprise 5 Gothons who are trying to take control of the ship.
			Each of them has an even uglier clown costume than the last. 
			They haven't pulled their weapons out yet, 
			as they see the active bomb under your arm 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 Gothons and make a leap for the door. 
				Right as you drop it a Gothon shoots you right in the back killing you. 
				As you die you see another Gothon frantically try to disarm the bomb. 
				You die knowing they will probably blow 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 and the Gothons put their hands up and start to sweat .
				You inch backward to the door, open it ,and then carefully place the bomb on the floor, pointing your blaster at it. 
				You then jump back through the door, punch the close button and blast the lock so the Gothon can't get out . 
				Now that the bomb is placed you 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 it to the escape pod before the whole ship explodes. 
			It seems like hardly any Gothons are on the ship, so your run is clear of interference. 
			You get to the chamber with the escape pods ,and now need to pick one to take. 
			Some of them could be damage but you don't have time to look.
			There's 5 pods, which one do you take?
		     """))
		
		good_pod =1
		guess = input('[pod #]> ')
		
		if int(guess) != good_pod:
			print(dedent("""
				You jump into pod {guess} and hit the eject button.
				The escapes pod  out into the void of space, 
				then implodes as the hull ruptures, crushing your body into jam jelly.
			     """))
			return 'death'	
		else:
			print(dedent("""
				You jump into pod {guess} and hit the eject button.
				The pod easily slides out into space heading to the planet below. 
				As it flies to the planet, you look back and see your ship implode then explode like a
				bright star, taking out the Gothon ship at the same time.
				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_scene
		
	def next_scene(self, scene_name):
		val = Map.scenes.get(scene_name)
		return val
	
	def opening_scene(self):
		return self.next_scene(self.start_scene)
 
a_map = Map('central_corridor')
a_game = Engine(a_map)
a_game.play()
The Gothons of planet Percal #25 haveinvaded your ship and desteoyed 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 afther getiing into an escape pod.
You're running down the central corridor to the Weapons Armory when a Gothon jumps out , 
red scaly skin, dark grimy filled body.
He's blocking the door to the Armory and about topull a weapon blast you.

> tell a joke

Lucky for you they made you learn Gothon insults in the academy. 
You tell the one Gothon joke you know:
Lbhe zbgure vf fb sng , jura fur fvgf nebhaq gur ubhfr, jura fur fvgf nebhaq gur ubhfr. 
The Gothon stops, tries not to laugh, then busts out laughing and can't move.
While he's laughing you run up and shoot him square in the head putting him down, then jump through the Weapon Armory door.


You do a dive roll into the Weapon Armory, crouch and scan the room for more Gothons that might be hiding. 
It's dead quiet, too quiet. You stand up and run to the far side of the room and find the neutron bomb in its container.
There's a keypad lock on the box and you need the code to get the bomb out. 
If you get the code wrong 10 times then the lock closes forever and you can't get the bomb. 
The code is 3 digits.

[keypad]> 123

The container clicks open and the seal breaks, letting gas out. 
You grab the neutron bomb and run as fast as you can to he bridge where you must place it in the right spot.


You burst onto the Bridge with the netron destruct bomb under your arm and surprise 5 Gothons who are trying to take control of the ship.
Each of them has an even uglier clown costume than the last. 
They haven't pulled their weapons out yet, 
as they see the active bomb under your arm and don't want to set it off.

> slowly place the bomb

You point your blaster at the bomb under your arm and the Gothons put their hands up and start to sweat .
You inch backward to the door, open it ,and then carefully place the bomb on the floor, pointing your blaster at it. 
You then jump back through the door, punch the close button and blast the lock so the Gothon can't get out . 
Now that the bomb is placed you run to the escape pod to get off this tin can.


You rush through the ship desperately trying to make it to the escape pod before the whole ship explodes. 
It seems like hardly any Gothons are on the ship, so your run is clear of interference. 
You get to the chamber with the escape pods ,and now need to pick one to take. 
Some of them could be damage but you don't have time to look.
There's 5 pods, which one do you take?

[pod #]> 1

You jump into pod {guess} and hit the eject button.
The pod easily slides out into space heading to the planet below. 
As it flies to the planet, you look back and see your ship implode then explode like a
bright star, taking out the Gothon ship at the same time.
You won!

You won! Good job.

#exe 44
When you are doing this kind of specialization, there are three ways that the parent and child classes
can interact:

  1. Actions on the child imply an action on the parent.
  2. Actions on the child override the action on the parent.
  3. Actions on the child alter the action on the parent.
    #alter:第三种使用继承的方式是覆盖的一种特殊情况,你希望在父类的版本运行之前或之后更改行为。
    你首先像上一个示例那样覆盖该函数,然后使用名为 super 的 Python 内置函数调用父类版本。
# ex44a.py implicit inheritance
class Parent(object):
	"""docstring for Parent"""
	def implicit(self):
		print("PARENT implicit():")
class Child(Parent):
	pass
#在子类 Child 下面使用 pass 是告诉 Python 你需要一个空块的方式。
#这样就创建了一个名为Child 的类,但是并没有什么新的内容需要定义。
dad = Parent()
son = Child()
dad.implicit()
son.implicit()

PARENT implicit():
PARENT implicit():
# ex44b.py Override Explicitly

class Parent(object):
	"""docstring for Parent"""

	def override(self):
		print("PARENT override()")

class Child(Parent):

	def override(self):
		print("CHILD override")

dad = Parent()
son = Child()

dad.override()
son.override()
PARENT override()
CHILD override
# ex44c.py Aleter Before of After
class Parent(object):
    
	"""docstring for Parent"""
	def altered(self):
		print("PARENT altered()")

class Child(Parent):

	def altered(self):
		print("CHILD, BEFORE PARENT altered()")
		super(Child, self).altered()
        #“使用参数 Child 和 self 来调用 super,
        #然后在它返回的任何地方调用 altered 函数
		print("CHILD, AFTER PARENT altered()")

dad = Parent()
son = Child()

dad.altered()
son.altered()


class ClassName(object):
	"""docstring for ClassName"""
	def __init__(self, arg):
		super(ClassName, self).__init__()
		self.arg = arg

PARENT altered()
CHILD, BEFORE PARENT altered()
PARENT altered()
CHILD, AFTER PARENT altered()

When to Use Inheritance or Composition:

  1. 无论如何都要避免多重继承,因为它太复杂而且不可靠。如果你被它困住了,那么
    要准备好了解一下类的层次结构,并花时间找出所有内容的来源。
  2. 使用组合将代码打包到模块中,这些模块可以用于许多不同的、不相关的地方和情
    境。
  3. 只有当存在明显相关的可复用代码片段,并且这些代码片段符合单个通用概念,或
    者由于你使用了某些东西而别无选择时,你才可以使用继承。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值