__init__的目的

ZCJ*_*ZCJ 4 python init

我已经完成了一些阅读,并且无法像我想的那样完全掌握这一点.我正在从LPTHW教程中做一些"选择你自己的冒险"游戏,这里是完整的脚本:http://codepad.org/YWVUlHnU

我不明白的是以下内容:

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
Run Code Online (Sandbox Code Playgroud)

我知道我们正在创建一个类,但为什么要定义__init__?后来我做了类似print self.quis[randint(0, len(self.quips)-1)]打印四个字符串中的一个的东西quips,但为什么我不会创建一个叫做的函数quips呢?

Ste*_*der 15

调用时Game("central_corridor"),将创建一个新对象,并Game.__init__()使用该新对象作为第一个参数(self)和"central_corridor"第二个参数调用该方法.自编写以来a_game = Game(...),您已分配a_game引用该新对象.

此图形可以使过程更容易理解:

Python对象创建

注意:该__new__方法由Python提供.它创建了作为第一个参数给出的类的新对象.内置__new__方法对剩余的参数没有任何作用.如果需要,可以覆盖该__new__方法并使用其他参数.

__init__()您的程序中存在的实际原因是在您创建startGame实例(您调用的实例)上设置属性a_game,以便第一次调用a_game.play()在您想要的位置开始.

你是对的quips.没有理由quips设置__init__().你可以把它变成一个类属性:

class Game(object):
    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." ]
    def __init__(self, start):
        self.start = start
Run Code Online (Sandbox Code Playgroud)


小智 5

更广泛地说__init__,__new__python类的鲜为人知且通常更危险的方法是执行初始化对象状态的工作.

为了您的特定对象是不是确有必要,我想有你能想到不被需要进行初始化的相当一些非常简单的数据存储类,但与Python更深层次的编程的现实是,几乎每一个更复杂的类需要被初始化为其基本状态.

另外,最重要的原因是让你的课程多用途:

class Foo(object):
    def __init__(self, word_of_power="Ni"):
        self.fact = "We are the knights who say %!" % word_of_power

>>> f = Foo()
>>> w = Foo("No!")
>>> print f.fact
"We are the knights who say Ni!"
>>> print w.fact
"We are the knights who say No!"
Run Code Online (Sandbox Code Playgroud)