r/learnpython • • Mar 10 '18
Can someone ELI5 what def __init__(self) means? I still don't get it :\
https://stackoverflow.com/questions/625083/python-init-and-self-what-do-they-do
Stack has a question just like this... But the explanations are insanely verbose and complex. I legit don't understand a word they're saying:
... the self variable represents the instance of the object itself. Most object-oriented languages pass this as a hidden parameter to the methods defined on an object; Python does not. You have to declare it explicitly. When you create an instance of the A class and call its methods, it will be passed automatically...
Just... What? The instance of the object? I don't understand what this means.
The init method is roughly what represents a constructor in Python. When you call A() Python creates an object for you, and passes it as the first parameter to the init method
Again, don't understand. I don't know what a constructor is. But even if I did, I don't understand why it is passing the parameter to the init method.
Can anyone help elucidate what is going on?
30
u/wolfgee Mar 10 '18 edited Mar 11 '18
This is my attempt to explain why you would use classes without all the technical lingo.
The short answer is :
__init__is a method which is called when you make an instance of a class.Now lets ELI5 break that sentence down, starting from the end:
turn_on_lights()function could turn the lights on in this house, all from your sweet raspberry pi app. Awesome!__init__method? What makes it different from other methods?__init__builds your house! It initializes it. You need a house before you can do cool things like adding doors and turning lights on, thats the job of__init__.self? self is the reference to the house before it is built. The blueprint essentially says: "this future house orselfwill have one door and the lights will be off."Now lets lay out the blueprint:
I am going to build a house
And now I'm going to add another door:
Now say you want to avoid that extra step of adding new doors after you built the house. You would rather build your house as
my_house = House(doors=2). That is possible by changing your__init__to look like this:10
u/Accipia Mar 10 '18 edited Mar 10 '18
self is simply a reference to the class you're working in. So if you'd have a class called Car, you could specify inside it self.wheels = 4. This would mean that if you'd later query say mycar.wheels it would return 4. Or you can use self.drive() to call the drive function.
__init__() is called when an instance of the class is created. So for example:
This would mean that every instance of the Car class you create would automatically call __init__() on creation, and set the wheels property to 4.
55
u/Yoru_Sulfur Mar 10 '18 edited Mar 10 '18
I'll give it a try, but fair warning I don't know if I'll be able to without using a lot of the same terminology in the sections you've already said you don't understand. Also, I'm just going to try to explain anything that I think you might need, so if there's stuff that you already know, bear with me.
For explanation let's use the same small class in that SO link.
This is the definition for an object with type
A. If I were to use this to actually make an object of typeA, I am doing something called instantiating it, or creating an instance. You'll have to understand that part because I can't think of a better way to describe it, and everything else will depend on that terminology. If you still don't get that part, stop reading and try asking me to clarify.So with that class definition, I could do the following
And
object_oneandobject_twoare both instances of classA.When creating an instance of a class, one might need to do some setup work, that's where the
__init__method comes in, it is called when an object is created (instantiated) and is used to do whatever setup might need to be done, in the example above that is setting an instance variable calledxto the string 'Hello`.A method of a class is a function that has access to the internals of the instance that it is called on. There's a lot to unpack there but it is necessary to understand. All methods (of which in or example there are two defined
__init__andmethod_a), take as their first parameter something that is usually (but only by convention) refereed to asself.selfis a reference to the object that the method was called on. So going back to some of the previous codeSo if you take a look at that, we set the
xinstance variable ofobject_oneto 'Goodbye', and when we calledmethod_aof it, it output 'Goodbye test', where withobject_twois output 'Hello test' because x was set to 'Hello' in the setup (__init__).I think I've been rambling for a little while know, and I'm not sure if I've been at all helpful.
Oh, and to explicitly answer your second question, a constructor is a method to create an instance of a class.
31
u/julsmanbr julsmanbr Mar 10 '18
So let's say you want to create a game and organize any weapons you create under a
Weaponclass. Even though there are going to be multiple different weapons, you know there will be a couple parameters that will be common to all of them, such as their name, their attack power, and their value when you try to sell them at a shop. So you create:By doing this, you are basically saying "I know all of my weapons will have these parameters in common: a name, a short description, a power and a value".
Now, for the confusing part: what's
__init__andselfdoing there? Well for starters, you can think osselfas a placeholder for your actual weapons that you will create. For example, if you create a weapon such as:you can now simply type
sword.nameto output the string passed as the sword name (which is simply'sword'- not very creative but oh well...). Same forsword.description,sword.powerand so on.The trick here is to notice that
sword.nameis literally ocuppying the space of your placeholderself.nameon the__init__method. The__init__method, in turn, tells Python how you want to structure each and every weapon you create. These weapons will also be commonly referred as instances of yourWeaponclass.One thing you might be wondering now is: isn't it obvious that
sword.nameshould display the sword's name? Why do I have to boringly define all these obvious statements on the__init__method? The thing is, you can come up other ways to work with your objects. For instance, you may want to have a full description of a weapon, which includes its name, power and value. But instead of having to do something like this everytime you want the full description of any given weapon:You can simply add a new line to your
__init__method, like:Now calling
sword.full_descwill return a beautifully formated string:Of course, the true power of the class lies in the fact that any other weapon you create will have the same functionalities of your sword. You simply need one line, such as:
And now you can even acess
twig.full_descfor the same functionality you had for your sword!81
u/robert_langdon83 Mar 10 '18
OP, I think you learn it from the wrong end. If you’d learn OOP basics, you wouldn’t ask what constructor is and what is the instance of the class. I’m not criticizing you. Just giving you a direction to dig in. Constructors, classes and objects are literally OOP 101. You have to learn it anyway, so now you have questions and it’s probably even easier to learn.
5
u/Sensorama Mar 10 '18 edited Mar 10 '18
First, I think you need to understand what is meant by object-oriented programming a bit more so that you have some context for why you want
__init__.You are probably used to seeing things like
num = 5and you may have a mental model that says the value 5 is stored in the variable num. That model works up to a point, but a more correct model is that
num = 5really doing something like
num = int(5)where int(5) is making an int object and storing 5 in it. The num variable knows where that object with a 5 in it is located in the computer memory and that location, or reference, is what is stored in num.
This 5 object is called an instance of the int class. There can be other instances of this class, for example, an int object that holds 2.
We want to be able to make our own classes of objects so they can store what we need in them. For example, a Person class might hold a name and an age value. A Person class might also have instance methods, which do things with that data, like add 1 to the age on a birthday.
In order to correctly setup a new object, a class should define an
__init__method. So if I want to make a Person instance, I can make it likeme = Person()now, this is the way people doing object-oriented programming are used to seeing objects being made. The Python interpreter sees this and (roughly) transforms it into
Person.__init__(me)to call the init method for a new Person instance and send the me variable to the method. In that
__init__, self is the first parameter, so any values assigned to self attributes (likeself.nameorself.age) are really being assigned to the me variable.Similarly, there might be an age method
def age(self): # in the Person classa call to this method has to come from a Person instance, like
me.age()again, the Python interpreter turns this into
Person.age(me)so me is the argument to the method and self is the parameter that gets that value.
In some ways, the whole self stuff is basically a convenience and a particular notation - you can think of what is happening underneath and it makes a little more sense.
3
u/Versuno Mar 10 '18
I just wanted to point out that you don't absolutely have to use "self". You could put any variable name in:
instead of self. It is just common practice to use self in Python. It is just a class level variable that allows the class to reference itself.
2
u/StupidHumanSuit Mar 10 '18
Somebody please correct me if I'm wrong, I'm still relatively new to this and often know the how of it but not the why. This comment is as much for OP as it is for me.
OP, speak it out loud to yourself to see if it makes it stick. It helps me. I talk through the code line by line and explain it.
OOP was explained to me like this: Think of a factory. The factory produces cars. Every car has certain characteristics that they share.
So, the "factory", the initial class definition, sets us up to produce more of whatever the factory produces... Like constructing something. That's a constructor. Like they say at Stack, Python doesn't really have a constructor, but a class is pretty close to one.
Think of init as initialize. You're initializing the parameters that the objects will inherit from the class. That word, inherit... You're gonna hear it a lot. So every instance, which is every object you instantiate based on this initial class, will inherit the parameters of the class. Instantiate basically means "create".
It seems confusing at first, but the documentation, while it seems dense, is your friend. Understanding it will make you a better programmer. Understanding OOP is essential to most modern programming. You will use it in almost every language you come across.
2
u/RangerPretzel Python 3.7+ Mar 10 '18
Like other people have said, you need to learn Object Oriented programming (OOP) first.
Python is pretty much like every other OOP in that once you understand one OOP, you can pretty much grasp the others very quickly. But if you don't get OOP, then it's very confusing.
As a side note, I hate that Python explicitly requires you to declare the
selfvariable (or whatever you want to call it.) Most languages do it for you without you even realizing it. And automatically call it something likeselforthisor something else.2
u/[deleted] Mar 10 '18
O boy, you're going at it the wrong way. You need to have object oriented programming basics down to understand this.
It's about constructors, classes and instances of classes.
Doesn't matter what language you look at. Get the basics, come back to Python and you'll get it. But the explanations in this thread are solid, if you can understand it. Stackoverflow isn't really beginner friendly, add to that the elitist mentality, and it's a shitshow if you're a beginner. Avoid it if you can.
1
u/groovitude Mar 10 '18
It might be easier to understand
__init__(self)if we start with another method first. Let's start by defining a simple class:Now we can build
Personobjects that can introduce themselves:We don't pass any parameters to the
introducemethod when we call it;selfis assigned to be the object calling it. We can make this explicit by calling the method from the class itself:Python objects have a number of "magic methods" -- they always start and end with double underscores, like
__init__, which is called when an object is "initialized," or created. We can't call it explicitly like we didintroduce, because the object's not assigned to a variable yet. But that's whyselfneeds to be passed -- you're calling the method of the class, and assigning everything to the object you're creating.As for the answers from Stack Overflow, it might be clearer if they said "the
selfvariable represents the instance of the class itself." In other words, an instance is an object of a given class. As for the constructor, it's what it sounds like -- it's a method building (or "constructing") the new object.1
u/lilith2k3 Mar 10 '18
Sure.
def is the word, used to tell python, that you are going to declare a function.
A function is a piece of code grouped by a name.
init is a special kind of function, therefore it has double underscores -dunder for short - around its name.
Every variable passed from the caller to the function is named. Here the name is "self" which is in general arbitrarily chosen by the writer of the code - but its good manners to use "self" for this special function.
A class is a collection of data an functions to mutate the data.
To use the class, you have to execute the initialization, e. g. bot=Robot() to initialize a Robot. During this initialization Python looks for the definition of the init method, which is called automatically. It does no harm, when none was defined. Calling this function automatically, Python fills in the content of the self variable.
1
u/tomk11 Apr 05 '18
A class is like a template for anything you want to represent. If you've ever used a list or tuplewhere different elements are used to represent different things then you really ought to using a class.
__ init __ is an example of what python sometimes calls 'magic' methods. That means they have a particular meaning to python. Init is called by default whenever you make a new 'instance' of your class. That's it.
Instance , object and class may all feel like jargon but they will suddenly make sense together. Classes are an abstract structure that make it easier to make 'objects' i.e things which share characteristics. For example a human may be a class, whereas Amy Winehouse may be an instance of that class. An object refers to an instance of any class.
0
u/PM-ME-SMILES-PLZ Mar 11 '18 edited Mar 11 '18
I can't give a clear concise answer, but you should google "Python Crash Course pdf" and read chapters 8 and 9 of that book (ch. 8 starts on page 166 of the PDF). This book has really helped me.
-3
u/RedLeaderRedLeader Mar 11 '18
Hey look bro, you can take a object oriented programming course at a community college for about 700-800 bucks, or, stop searching your python problem and start searching for object oriented programming.
2
u/[deleted] Mar 10 '18
[removed] — view removed comment