我已经完成了一些阅读,并且无法完全按照我的意愿去理解它。我正在一点点“选择自己的冒险”,从LPTHW教程游戏,以下是完整的脚本:http://codepad.org/YWVUlHnU__init__的用途
什么我不明白的是:
class Game(object):
def __init__(self, start):
self.quips = [
"You died. Please try again.",
"You lost, better luck next time.",
"Things didn't work out well. You'll need to start over."
"You might need to improve your skills. Try again."
]
self.start = start
我明白咱”重新创建一个类,但为什么定义__init__
?后来我做了一些像print self.quis[randint(0, len(self.quips)-1)]
这样的打印quips
中四个字符串之一的东西,但为什么我不会创建一个叫做quips
的函数呢?
我想如果我创建了“Game”类的实例,我使用的任何属性都将决定游戏的开始位置。因此,如果我想通过在游戏类中的'laser_weapon_armory'函数开始游戏,我会做'a_game = game(“laser_weapon_armory”)'然后''a_game.play()'。 '__init__'与这个有什么关系? – ZCJ 2012-02-16 21:06:45
__init__方法设置对象的基本状态......想象一下,如果需要先连接到数据库并首先下载一些数据以准备好自己,那么在做其他事情之前,您应该在__init__中执行此操作。这就像是要从经销商处购买汽车......没有__init__,你会得到一个没有车轮,没有引擎的汽车物体,但如果你愿意,你仍然可以car.drive()。 – michaelfilms 2012-02-16 21:25:20
@ZCJ当你写'Game(“laser_weapon_armory”)'时,实际发生的是一个新的'Game'实例被创建,我们称它为'obj'(它现在真的没有名字),然后Python _automatically_运行'Game .__ init __(obj,“laser_weapon_armory”)'并返回'obj'(你最终分配给名字'a_game')。 '__init__'将'obj.start'设置为''laser_weapon_armory“''。当你运行'a_game.play()'时,实际发生的事情是Python正在运行'Game.play(a_game)''self'参数被'a_game'填充,所以'self.start'是''laser_weapon_armory “'当你调用'a_game.play()'时。 – 2012-02-16 21:52:10