🌐
GeeksforGeeks
geeksforgeeks.org › python › __init__-in-python
__init__ in Python - GeeksforGeeks
__init__ method in Python is a constructor. It runs automatically when a new object of a class is created. Its main purpose is to initialize the object’s attributes and set up its initial state.
Published   September 12, 2025
🌐
GeeksforGeeks
geeksforgeeks.org › python › what-is-__init__-py-file-in-python
What is __Init__.Py File in Python? - GeeksforGeeks
July 23, 2025 - __init__.py is a special file used in Python to define packages and initialize their namespaces. It can contain an initialization code that runs when the package is imported. Without this file, Python won't recognize a directory as a package.
Discussions

class - Why do we use __init__ in Python classes? - Stack Overflow
I am having trouble understanding the Initialization of classes. What's the point of them and how do we know what to include in them? Does writing in classes require a different type of thinking v... More on stackoverflow.com
🌐 stackoverflow.com
What does __init__ and self do in python?
What does __init__ and self do in Python? __init__ is used to initialise the created class instance, in practice this mostly means setting the attributes the methods expect it to have. self refers to the current instance, although the name itself isn't special in any way whatsoever - you could use whatever valid identifier you wanted, although I don't particularly recommend deviating from established practices here because we're used to self. As for why your code doesn't do what you think, you never called that method. Random_Player = Game('Male', 19) Random_Player.score() As a side note I recommend reading PEP-8, PEP-257, and PEP-484 as the official style guide. More on reddit.com
🌐 r/learnpython
40
116
January 19, 2024
oop - What do __init__ and self do in Python? - Stack Overflow
I'm learning the Python programming language and I've came across something I don't fully understand. In a method like: def method(self, blah): def __init__(?): .... .... What does More on stackoverflow.com
🌐 stackoverflow.com
Can Someone explain to me what is self and init in python?
watch this . More on reddit.com
🌐 r/learnpython
39
243
November 29, 2022
🌐
GeeksforGeeks
geeksforgeeks.org › videos › __init__-in-python
__init__ in Python - GeeksforGeeks | Videos
In this video, we will explore the concept of __init__ in Python, which is an essential part of object-oriented programming in Python. The __init__ method is used to initialize the state of an object.
Published   June 18, 2024
Views   1K
🌐
GeeksforGeeks
geeksforgeeks.org › python › __init__-in-python
__init__ in Python - GeeksforGeeks
__init__ method in Python is a constructor. It runs automatically when a new object of a class is created. Its main purpose is to initialize the object’s attributes and set up its initial state.
Published   September 12, 2025
🌐
GeeksforGeeks
geeksforgeeks.org › python › understanding-the-role-of-parent-classs-init-in-python-inheritance
Understanding the Role of Parent Class's init() in Python Inheritance - GeeksforGeeks
July 23, 2025 - The __init__() method also known as a constructor is a special method in Python that gets called when an instance of a class is created.
🌐
W3Schools
w3schools.com › python › gloss_python_class_init.asp
Python __init__() Function
Note: The __init__() method is called automatically every time the class is being used to create a new object. Python Syntax Tutorial Class Create Class Object Methods self Modify Object Properties Delete Object Properties Delete Object Class pass Statement ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com
🌐
GeeksforGeeks
geeksforgeeks.org › python › is-__init__-a-private-method-in-python
Is __init__() a private method in Python? - GeeksforGeeks
July 23, 2025 - So we can conclude that __init__ is not a private method, In Python, there's nothing like private/protected by technique, it's just a convention, and we can access private/protected methods. It's more like a convention, rather than a technique.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-super-with-__init__-method
Python Super() With __Init__() Method - GeeksforGeeks
July 23, 2025 - In this example, below Python code defines two classes, `Animal` and `Dog`, with the `Dog` class inheriting from `Animal`. The `__init__` method in each class initializes attributes (`name` in `Animal` and `name` and `breed` in `Dog`).
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-init-vs-new
Python __init__ vs __new__ - GeeksforGeeks
July 23, 2025 - __new__ method is responsible for creating the instance. It’s called before __init__ and is where the object itself is actually created. The super().__new__(cls) call creates the new instance, and then it’s returned so that Python can continue with the initialization.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-classes-and-objects
Python Classes and Objects - GeeksforGeeks
Dog("Buddy", 3) creates an object and passes values to __init__(). self.name and self.age store the object’s name and age. dog1.name accesses the object’s instance attribute and dog1.species accesses the shared class attribute. __str__ method allows us to define a custom string representation of an object. By default, when we print an object or convert it to a string using str(), Python uses the default implementation, which returns a string like <__main__.ClassName object at 0x00000123>.
Published   1 week ago
🌐
GeeksforGeeks
geeksforgeeks.org › python › __init_subclass__-in-python
__init_subclass__ in Python - GeeksforGeeks
July 15, 2025 - As per inheritance, we know that a superclass reference can hold its subclass reference. We all know that the behavior of the superclass can be altered according to the implementation of its sub-class(es). But now, we can alter the behavior of the sub-class(es) by using __init_subclass__ Python3 1== # defining a SuperClass class SuperClass: # defining __init_subclass__ method def __init_subclass__(cls, **kwargs): cls.default_name ="Inherited Class" # defining a SubClass class SubClass(SuperClass): # an attribute of SubClass default_name ="SubClass" print(default_name) subclass = SubClass() print(subclass.default_name) Output : SubClass Inherited Class Understanding the code ·
Top answer
1 of 9
331

By what you wrote, you are missing a critical piece of understanding: the difference between a class and an object. __init__ doesn't initialize a class, it initializes an instance of a class or an object. Each dog has colour, but dogs as a class don't. Each dog has four or fewer feet, but the class of dogs doesn't. The class is a concept of an object. When you see Fido and Spot, you recognise their similarity, their doghood. That's the class.

When you say

class Dog:
    def __init__(self, legs, colour):
        self.legs = legs
        self.colour = colour

fido = Dog(4, "brown")
spot = Dog(3, "mostly yellow")

You're saying, Fido is a brown dog with 4 legs while Spot is a bit of a cripple and is mostly yellow. The __init__ function is called a constructor, or initializer, and is automatically called when you create a new instance of a class. Within that function, the newly created object is assigned to the parameter self. The notation self.legs is an attribute called legs of the object in the variable self. Attributes are kind of like variables, but they describe the state of an object, or particular actions (functions) available to the object.

However, notice that you don't set colour for the doghood itself - it's an abstract concept. There are attributes that make sense on classes. For instance, population_size is one such - it doesn't make sense to count the Fido because Fido is always one. It does make sense to count dogs. Let us say there're 200 million dogs in the world. It's the property of the Dog class. Fido has nothing to do with the number 200 million, nor does Spot. It's called a "class attribute", as opposed to "instance attributes" that are colour or legs above.

Now, to something less canine and more programming-related. As I write below, class to add things is not sensible - what is it a class of? Classes in Python make up of collections of different data, that behave similarly. Class of dogs consists of Fido and Spot and 199999999998 other animals similar to them, all of them peeing on lampposts. What does the class for adding things consist of? By what data inherent to them do they differ? And what actions do they share?

However, numbers... those are more interesting subjects. Say, Integers. There's a lot of them, a lot more than dogs. I know that Python already has integers, but let's play dumb and "implement" them again (by cheating and using Python's integers).

So, Integers are a class. They have some data (value), and some behaviours ("add me to this other number"). Let's show this:

class MyInteger:
    def __init__(self, newvalue):
        # imagine self as an index card.
        # under the heading of "value", we will write
        # the contents of the variable newvalue.
        self.value = newvalue
    def add(self, other):
        # when an integer wants to add itself to another integer,
        # we'll take their values and add them together,
        # then make a new integer with the result value.
        return MyInteger(self.value + other.value)

three = MyInteger(3)
# three now contains an object of class MyInteger
# three.value is now 3
five = MyInteger(5)
# five now contains an object of class MyInteger
# five.value is now 5
eight = three.add(five)
# here, we invoked the three's behaviour of adding another integer
# now, eight.value is three.value + five.value = 3 + 5 = 8
print eight.value
# ==> 8

This is a bit fragile (we're assuming other will be a MyInteger), but we'll ignore now. In real code, we wouldn't; we'd test it to make sure, and maybe even coerce it ("you're not an integer? by golly, you have 10 nanoseconds to become one! 9... 8....")

We could even define fractions. Fractions also know how to add themselves.

class MyFraction:
    def __init__(self, newnumerator, newdenominator):
        self.numerator = newnumerator
        self.denominator = newdenominator
        # because every fraction is described by these two things
    def add(self, other):
        newdenominator = self.denominator * other.denominator
        newnumerator = self.numerator * other.denominator + self.denominator * other.numerator
        return MyFraction(newnumerator, newdenominator)

There's even more fractions than integers (not really, but computers don't know that). Let's make two:

half = MyFraction(1, 2)
third = MyFraction(1, 3)
five_sixths = half.add(third)
print five_sixths.numerator
# ==> 5
print five_sixths.denominator
# ==> 6

You're not actually declaring anything here. Attributes are like a new kind of variable. Normal variables only have one value. Let us say you write colour = "grey". You can't have another variable named colour that is "fuchsia" - not in the same place in the code.

Arrays solve that to a degree. If you say colour = ["grey", "fuchsia"], you have stacked two colours into the variable, but you distinguish them by their position (0, or 1, in this case).

Attributes are variables that are bound to an object. Like with arrays, we can have plenty colour variables, on different dogs. So, fido.colour is one variable, but spot.colour is another. The first one is bound to the object within the variable fido; the second, spot. Now, when you call Dog(4, "brown"), or three.add(five), there will always be an invisible parameter, which will be assigned to the dangling extra one at the front of the parameter list. It is conventionally called self, and will get the value of the object in front of the dot. Thus, within the Dog's __init__ (constructor), self will be whatever the new Dog will turn out to be; within MyInteger's add, self will be bound to the object in the variable three. Thus, three.value will be the same variable outside the add, as self.value within the add.

If I say the_mangy_one = fido, I will start referring to the object known as fido with yet another name. From now on, fido.colour is exactly the same variable as the_mangy_one.colour.

So, the things inside the __init__. You can think of them as noting things into the Dog's birth certificate. colour by itself is a random variable, could contain anything. fido.colour or self.colour is like a form field on the Dog's identity sheet; and __init__ is the clerk filling it out for the first time.

Any clearer?

EDIT: Expanding on the comment below:

You mean a list of objects, don't you?

First of all, fido is actually not an object. It is a variable, which is currently containing an object, just like when you say x = 5, x is a variable currently containing the number five. If you later change your mind, you can do fido = Cat(4, "pleasing") (as long as you've created a class Cat), and fido would from then on "contain" a cat object. If you do fido = x, it will then contain the number five, and not an animal object at all.

A class by itself doesn't know its instances unless you specifically write code to keep track of them. For instance:

class Cat:
    census = [] #define census array

    def __init__(self, legs, colour):
        self.colour = colour
        self.legs = legs
        Cat.census.append(self)

Here, census is a class-level attribute of Cat class.

fluffy = Cat(4, "white")
spark = Cat(4, "fiery")
Cat.census
# ==> [<__main__.Cat instance at 0x108982cb0>, <__main__.Cat instance at 0x108982e18>]
# or something like that

Note that you won't get [fluffy, sparky]. Those are just variable names. If you want cats themselves to have names, you have to make a separate attribute for the name, and then override the __str__ method to return this name. This method's (i.e. class-bound function, just like add or __init__) purpose is to describe how to convert the object to a string, like when you print it out.

2 of 9
30

To contribute my 5 cents to the thorough explanation from Amadan.

Where classes are a description "of a type" in an abstract way. Objects are their realizations: the living breathing thing. In the object-orientated world there are principal ideas you can almost call the essence of everything. They are:

  1. encapsulation (won't elaborate on this)
  2. inheritance
  3. polymorphism

Objects have one, or more characteristics (= Attributes) and behaviors (= Methods). The behavior mostly depends on the characteristics. Classes define what the behavior should accomplish in a general way, but as long as the class is not realized (instantiated) as an object it remains an abstract concept of a possibility. Let me illustrate with the help of "inheritance" and "polymorphism".

    class Human:
        gender
        nationality
        favorite_drink
        core_characteristic
        favorite_beverage
        name
        age

        def love    
        def drink
        def laugh
        def do_your_special_thing                

    class Americans(Humans)
        def drink(beverage):
            if beverage != favorite_drink: print "You call that a drink?"
            else: print "Great!" 

    class French(Humans)
        def drink(beverage, cheese):
            if beverage == favourite_drink and cheese == None: print "No cheese?" 
            elif beverage != favourite_drink and cheese == None: print "Révolution!"

    class Brazilian(Humans)
        def do_your_special_thing
            win_every_football_world_cup()

    class Germans(Humans)
        def drink(beverage):
            if favorite_drink != beverage: print "I need more beer"
            else: print "Lecker!" 

    class HighSchoolStudent(Americans):
        def __init__(self, name, age):
             self.name = name
             self.age = age

jeff = HighSchoolStudent(name, age):
hans = Germans()
ronaldo = Brazilian()
amelie = French()

for friends in [jeff, hans, ronaldo]:
    friends.laugh()
    friends.drink("cola")
    friends.do_your_special_thing()

print amelie.love(jeff)
>>> True
print ronaldo.love(hans)
>>> False

Some characteristics define human beings. But every nationality differs somewhat. So "national-types" are kinda Humans with extras. "Americans" are a type of "Humans " and inherit some abstract characteristics and behavior from the human type (base-class) : that's inheritance. So all Humans can laugh and drink, therefore all child-classes can also! Inheritance (2).

But because they are all of the same kind (Type/base-class : Humans) you can exchange them sometimes: see the for-loop at the end. But they will expose an individual characteristic, and thats Polymorphism (3).

So each human has a favorite_drink, but every nationality tend towards a special kind of drink. If you subclass a nationality from the type of Humans you can overwrite the inherited behavior as I have demonstrated above with the drink() Method. But that's still at the class-level and because of this it's still a generalization.

hans = German(favorite_drink = "Cola")

instantiates the class German and I "changed" a default characteristic at the beginning. (But if you call hans.drink('Milk') he would still print "I need more beer" - an obvious bug ... or maybe that's what i would call a feature if i would be a Employee of a bigger Company. ;-)! )

The characteristic of a type e.g. Germans (hans) are usually defined through the constructor (in python : __init__) at the moment of the instantiation. This is the point where you define a class to become an object. You could say breath life into an abstract concept (class) by filling it with individual characteristics and becoming an object.

But because every object is an instance of a class they share all some basic characteristic-types and some behavior. This is a major advantage of the object-orientated concept.

To protect the characteristics of each object you encapsulate them - means you try to couple behavior and characteristic and make it hard to manipulate it from outside the object. That's Encapsulation (1)

🌐
GeeksforGeeks
geeksforgeeks.org › python › what-does-super-__init__args-kwargs-do-in-python
What Does Super().__Init__(*Args, **Kwargs) Do in Python? - GeeksforGeeks
July 23, 2025 - Constructor Method: When you create a new thing (object) in Python, __init__() is a special method that gets it ready by setting up its initial characteristics or qualities.
🌐
Mimo
mimo.org › glossary › python › init-function
Python __init__() Function: Syntax, Usage, and Examples
The Python __init__() function serves as the constructor method for classes. It initializes newly created objects and allows you to assign values to object properties or run startup procedures when an instance is created.
🌐
Reddit
reddit.com › r/learnpython › what does __init__ and self do in python?
r/learnpython on Reddit: What does __init__ and self do in python?
January 19, 2024 -

I don't really understand, I read many reddit posts, websites about it but still I can't use it properly.I don't know what does it do, what's the point of having it

I tried a code like this but the result is not what I expected. I thought it prints "wow" or "goodbye".

class Game():
    def __init__(self, Character, Age):
        self.Character = Character
        self.Age = Age

    def score(self):
        if self.Age >= 18:
           print("wow")
        else:
           print("goodbye")

Random_Player = Game('Male', 19) 
print(Random_Player)

Results

<__main__.Game object at 0x0000013AD63D85D0>
Top answer
1 of 21
93
What does __init__ and self do in Python? __init__ is used to initialise the created class instance, in practice this mostly means setting the attributes the methods expect it to have. self refers to the current instance, although the name itself isn't special in any way whatsoever - you could use whatever valid identifier you wanted, although I don't particularly recommend deviating from established practices here because we're used to self. As for why your code doesn't do what you think, you never called that method. Random_Player = Game('Male', 19) Random_Player.score() As a side note I recommend reading PEP-8, PEP-257, and PEP-484 as the official style guide.
2 of 21
34
Game is a class with 2 member variables and one method attached to it. __init__ is called when you create a new instance of the Game class. It expects two arguments, and assigns them to the member variables of the object. The function score checks the Age member and prints one of two messages depending on what value Age holds. So when you run the line Random_Player = Game('male' 19) You create a new instance of a Game object. __init__ is called, which makes the assignments to the member variables, and the new object is then assigned to the variable Random_Player. On the next line you print Random_Player. Printing anything that's not already a string causes Python to try to convert it to a string. It does this by looking for two functions in the class: __str__ or __repr__. Without going into more detail, if either of these exist, Python will use that function to convert any Game object to a string when asked. You'll notice that like __init__ both of those functions use double underscores. These are special functions that have specific meanings when you define them for a class, and option will use them automatically for different things. Since neither of those exist however, it uses the default functionality built into Python, printing out the name of the type and the memory address that specific variable is being stored at. Nowhere in the code do you ever call the score function, so that code is never run. If you want it to run, you call it like: Random_Player.score() Note that you don't print the call to score, the score function calls print itself, so all you need to do is call that function and it will print out the message based on Random_Player.Age. Hopefully this helps you understand how all these things piece together, and why your code isn't working in write the way you expect.
Top answer
1 of 16
717

In this code:

class A(object):
    def __init__(self):
        self.x = 'Hello'

    def method_a(self, foo):
        print self.x + ' ' + foo

... 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, as in ...

a = A()               # We do not pass any argument to the __init__ method
a.method_a('Sailor!') # We only pass a single argument

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. Any additional parameters (e.g., A(24, 'Hello')) will also get passed as arguments--in this case causing an exception to be raised, since the constructor isn't expecting them.

2 of 16
318

Yep, you are right, these are oop constructs.

__init__ is the constructor for a class. The self parameter refers to the instance of the object (like this in C++).

class Point:
    def __init__(self, x, y):
        self._x = x
        self._y = y

The __init__ method gets called after memory for the object is allocated:

x = Point(1,2)

It is important to use the self parameter inside an object's method if you want to persist the value with the object. If, for instance, you implement the __init__ method like this:

class Point:
    def __init__(self, x, y):
        _x = x
        _y = y

Your x and y parameters would be stored in variables on the stack and would be discarded when the init method goes out of scope. Setting those variables as self._x and self._y sets those variables as members of the Point object (accessible for the lifetime of the object).

N.B. Some clarification of the use of the word "constructor" in this answer. Technically the responsibilities of a "constructor" are split over two methods in Python. Those methods are __new__ (responsible for allocating memory) and __init__ (as discussed here, responsible for initialising the newly created instance).

🌐
MicroPyramid
micropyramid.com › blog › understand-self-and-__init__-method-in-python-class
Understanding Self and __init__ Method in Python Class | MicroPyramid
self represents the instance of the class. By using the "self" keyword we can access the attributes and methods of the class in python. "__init__" is a reseved method in python classes. It is known as a constructor in object oriented concepts.
🌐
Index.dev
index.dev › blog › what-is-init-in-python
Master Python Objects: The Ultimate Guide to the __init__ Method
June 10, 2024 - This unique function is triggered automatically when a class creates an object. This function lets us do any setup or configuration chores required and initialise the properties of an object.
🌐
Real Python
realpython.com › python-init-py
What Is Python's __init__.py For? – Real Python
July 9, 2025 - You can use __init__.py to explicitly define a package’s public API by importing specific modules or functions into the package namespace. The Python convention of using leading underscores helps indicate to users which objects are intended as non-public, although this convention can still be bypassed.