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 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:
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
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!"
__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.