Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Purpose of __init__

Tags:

python

init

I've done some reading and can't grasp this as fully as I'd like to. I'm making a little "choose your own adventure" game from the LPTHW tutorial, here's the full script: http://codepad.org/YWVUlHnU

What I don't understand is the following:

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

I get that we're creating a class, but why define __init__? Later on I do stuff like print self.quis[randint(0, len(self.quips)-1)] which prints one of the four strings in quips, but why wouldn't I just create a function called quips or something?

like image 407
ZCJ Avatar asked Nov 29 '22 15:11

ZCJ


1 Answers

When you call Game("central_corridor"), a new object is created and the Game.__init__() method is called with that new object as the first argument (self) and "central_corridor" as the second argument. Since you wrote a_game = Game(...), you have assigned a_game to refer to that new object.

This graphic may make the process easier to understand:

Python object creation

Note: The __new__ method is provided by Python. It creates a new object of the class given as the first argument. The built-in __new__ method doesn't do anything with the remaining arguments. If you need to, you can override the __new__ method and utilize the other arguments.

The practical reason __init__() exists in your program is set the start attribute on the Game instance you create (the one you call a_game), so that the first call to a_game.play() starts in the location where you want it to.

You're right about quips. There is no reason to have quips be set up in __init__(). You can just make it a class attribute:

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
like image 122
Steven T. Snyder Avatar answered Dec 19 '22 06:12

Steven T. Snyder