4

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?

3 Answers 3

15

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
5
  • I thought if I created an instance of the class Game, whatever attribute I use will determine where the game starts. So if I want the game to start by going to the laser_weapon_armory function in the class Game, I'd do a_game = game("laser_weapon_armory") then a_game.play(). What does __init__ have to do with this?
    – ZCJ
    Commented Feb 16, 2012 at 21:06
  • The init method sets up the base state of your object ... imagine if it needed to connect to a database and download some data first to prepare itself, you'd do that in the init before doing other things. It's like going to buy a car from a dealer ... without the init you'd get a car object with no wheels, no engine, but you could still car.drive() it if you wanted to. Commented Feb 16, 2012 at 21:25
  • 1
    @ZCJ When you write Game("laser_weapon_armory"), what actually happens is a new Game instance is created, let's call it obj (it really has no name at this point), and then Python automatically runs Game.__init__(obj, "laser_weapon_armory") and returns obj (which you end up assigning to the name a_game). obj.start is set to "laser_weapon_armory" by __init__. When you run a_game.play(), what's actually happening is Python is running Game.play(a_game) - the self argument is filled in with a_game, so self.start is "laser_weapon_armory" when you call a_game.play(). Commented Feb 16, 2012 at 21:52
  • @Series8217: Very nice answer - just being picky, __new__ method is passed the same arguments that are later passed to __init__ not just the class.
    – jsbueno
    Commented Feb 17, 2012 at 2:19
  • @jsbueno You are correct of course. I'll add a note about it. Commented Feb 17, 2012 at 17:11
5

More broadly __init__ and the lesser known and often more dangerous __new__ methods of a python class are there to do the job of initializing the state of your object.

For your particular object it's not truly necessary and I suppose there are quite a few very simple data storage classes you could think of as not being needed to be initialized, but the reality of deeper programming with python is that virtually every more complex class needs to be initialized to its base state.

Additionally the big reason is to make your class multipurpose:

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!"
3
  • By "multipurpose", you mean I can use this class to create instances like Foo() as well as instances with an attribute like Foo("No!")? And you're saying that the benefit of making it multipurpose is so that these both will work?
    – ZCJ
    Commented Feb 16, 2012 at 22:22
  • @ZCJ, just to keep terminology straight, note that in the statement Foo("No!"), "No!" is not an "attribute." It's an argument, and it works the same as the argument to any function. In fact, it can be helpful to think of Foo as a special kind of function that takes some number of arguments and returns an object of type Foo. self.fact, on the other hand, is an attribute.
    – senderle
    Commented Feb 16, 2012 at 22:41
  • Ok, thanks very much for the clarification- hammering down the terminology is something I'm trying to work on. So w.fact in your response is an attribute, but when assigning variables f and w to different instances of foo, foo can take an argument within the parenthesis since the class allows it. Sound right?
    – ZCJ
    Commented Feb 16, 2012 at 23:00
1

__init__ works as constructor here. So when the game instance is created, the __init__ method is called. If you define another method to set up quips, you'll have to call it explicitly.

1
  • Strictly speaking, __new__ is the constructor and __init__ is the "initializator".
    – glglgl
    Commented Sep 28, 2013 at 9:06

Not the answer you're looking for? Browse other questions tagged or ask your own question.