I’ve been striving mightily for three days to wrap my head around __init__ and “self”, starting at Learn Python the Hard Way exercise 42, and moving on to read parts of the Python documentation, Alan Gauld’s chapter on Object-Oriented Programming, Stack threads like this one on “self”, and this one, and frankly, I’m getting ready to hit myself in the face with a brick until I pass out.
That being said, I’ve noticed a really common convention in initial __init__ definitions, which is to follow up with (self, foo) and then immediately declare, within that definition, that self.foo = foo.
From LPTHW, ex42:
class Game(object):
def __init__(self, start):
self.quips = ["a list", "of phrases", "here"]
self.start = start
From Alan Gauld:
def __init__(self,val): self.val = val
I’m in that horrible space where I can see that there’s just One Big Thing I’m not getting, and I it’s remaining opaque no matter how much I read about it and try to figure it out. Maybe if somebody can explain this little bit of consistency to me, the light will turn on. Is this because we need to say that “foo,” the variable, will always be equal to the (foo) parameter, which is itself contained in the “self” parameter that’s automatically assigned to the def it’s attached to?
You might want to study up on object-oriented programming.
Loosely speaking, when you say
you’re saying:
I have a type of “thing” named
GameWhenever a new
Gameis created, it will demand me for some extra piece of information,start. (This is because theGame‘s initializer, named__init__, asks for this information.)The initializer (also referred to as the “constructor”, although that’s a slight misnomer) needs to know which object (which was created just a moment ago) it’s initializing. That’s the first parameter — which is usually called
selfby convention (but which you could call anything else…).The game probably needs to remember what the
startI gave it was. So it stores this information “inside” itself, by creating an instance variable also namedstart(nothing special, it’s just whatever name you want), and assigning the value of thestartparameter to thestartvariable.Hope this explains what’s happening.