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?
When you call
Game("central_corridor"), a new object is created and theGame.__init__()method is called with that new object as the first argument (self) and"central_corridor"as the second argument. Since you wrotea_game = Game(...), you have assigneda_gameto refer to that new object.This graphic may make the process easier to understand:
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 thestartattribute on theGameinstance you create (the one you calla_game), so that the first call toa_game.play()starts in the location where you want it to.You’re right about
quips. There is no reason to havequipsbe set up in__init__(). You can just make it a class attribute: