OOP & Syntax - Ex 43 - Learn Python the Hard Way



我是编码的新手,完全是个菜鸟。我一直很喜欢看Zed Shaw的书"Learn Python 3 the Hard Way"——但是当我进入这个练习和OOP时,突然间一切都变得没有意义了。

我真的需要更有经验的人帮助,了解如何实际将此代码"翻译成英语",以便我可以遵循它正在做的事情......理想情况下,还要弄清楚如何编写这样的代码。

在Stack Overflow上还有另一篇类似的帖子 - 但我真的希望那里有慷慨的人可以和我一起深入研究,这也将被证明对其他在OOP中挣扎的菜鸟有益。

我已经逐行包含我的问题...我认为到目前为止,有人可以做的最有用的事情之一就是和我一起检查这段代码的语法。我试图用一个序列来考虑它:(1( xyz 被输入 (2( abc 发生 (3( efg 被返回......但是嵌套关系太多了,如果没有更有经验的人的帮助,我无法解析所有内容。

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

Q1:这些行仅用于调试目的,对吗?

class Engine(object):
def __init__(self, scene_map):
self.scene_map = scene_map

Q2:我的麻烦从OOP开始。我怎样才能直观地理解"init"以及如何使用它?我认为"自我"="a_game"...但是这一行self.scene_map = scene_map在代码的其余上下文中甚至做什么?

def play(self):
current_scene = self.scene_map.opening_scene()
last_scene = self.scene_map.next_scene('finished')

Q3:这 2 行中发生了很多事情(也涉及 Map 类(......这到底在说什么?

while current_scene != last_scene:
next_scene_name = current_scene.enter()
current_scene = self.scene_map.next_scene(next_scene_name)

Q4:我得到了其中的"同时"部分...但随后我对接下来的 2 行"next_scene_name = ..."和"current_scene = ..."就像播放函数中的台词一样,我很想知道专业程序员是如何阅读的。

current_scene.enter()

Q5:我相信这是启动操作的代码的核心......但是它如何与每个场景结束时返回的值交互(这大概会导致下一个场景(?每个场景都以"返回'xyz'"结尾——我不明白这怎么够。

class CentralCorridor(Scene):
def enter(self):
# print story-line here...
action = input("> ")
if action == "xyz":
return 'laser_weapon_armory'
# rest omitted...
class LaserWeaponArmory(Scene):
def enter(self):
# action & choices go here...
return 'xyz'
class Map(object):
scenes = {
'central_corridor': CentralCorridor(),
'laser_weapon_armory': LaserWeaponArmory(),
# more...
}
def __init__(self, start_scene):
self.start_scene = start_scene

请参阅问题 2...

def next_scene(self, scene_name):
val = Map.scenes.get(scene_name)
return val

Q6:我知道当调用这个函数时,它会从 scene['scene_name'] 返回键的值 - 但实际上首先调用这个next_scene函数是什么?当"val"返回时,它会去哪里?

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

Q7:由于a_map被定义为带有参数"central_corridor"的类 Map,我知道这是在说"返回self.next_scene('central_corridor'("......但在那之后我又迷路了!这到底是什么意思?

a_map = Map('central_corridor')
a_game = Engine(a_map)
a_game.play()

我明白的这些最后几行...但是,同样,一旦我开始将它们重新插入代码的其余部分,我很快就会迷失方向。

就是这样!我知道这很多 - 我理解人们是否想因为我是一个菜鸟而对我投反对票,但我真的很想了解OOP,这对我来说是相当具有挑战性的。

甚至我在学习LearnPython the Hard Way 的 OOPS 时也遇到了同样的问题,所以我建议你从Interactive Python学习 OOPS。

http://interactivepython.org/runestone/static/pythonds/Introduction/ObjectOrientedProgramminginPythonDefiningClasses.html

一旦你熟悉了OOPS的概念,你就可以继续学习Python。我希望它对你有所帮助。这不是您问题的答案,但我没有足够的代表发表评论。

最新更新