🌐
Medium
medium.com › @jazeem.lk › understanding-new-and-init-in-python-fbede74bc1ba
Understanding __new__() and __init__() in Python | by azeem jainulabdeen | Medium
November 15, 2024 - In Python, two special methods, __new__() and __init__(), play a crucial role in object creation and initialization. While both methods are related to how objects are constructed, they serve distinct purposes. To understand the difference between them, let’s examine two examples: a Singleton pattern implemented in the Connection class and a factory-based object creation in the Factory class.
🌐
Team Treehouse
teamtreehouse.com › community › real-world-application-of-init
real world application of __init__ (Example) | Treehouse Community
June 25, 2020 - I understand the code as in I know what to do when it tells me to do it, but I do not understand why you would want to use the Init. I also do not understand why it have me set the self.name = name and so on.
Discussions

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
Understanding classes, init and self
Could you explain this code excerpt? I am learning and trying to get in touch with the logic of classes · The __init__ method initialises a new instance (object) of the class NewWindow. The actual creation of the instance is done by a separate method __new__, before __init__ is called. More on discuss.python.org
🌐 discuss.python.org
19
0
February 16, 2024
🌐
Quora
quora.com › What-kind-of-code-should-I-write-put-in-init__-py-in-Python-applications
What kind of code should I write/put in ‘__init__.py’ in Python applications? - Quora
It’s helpful to understand the a module is just a file of Python code. So if I put the following in mymodule.py: ... …then when I import mymodule, I have access to that function (and any other functions, variables, or classes) in that module: ... A package is simply a directory/folder (or a hierarchy of directories) containing one or more modules. Some packages you may be familiar with are numpy, scipy, pandas, etc. The __init__.py file is an initialization file which lives in each subdir of the package.
🌐
Medium
geekpython.medium.com › init-and-call-in-python-what-they-do-and-how-to-use-3b72346ad481
__init__ and __call__ In Python — What They Do And How To Use | by Sachin Pal | Medium
March 1, 2023 - The __init__ for the class Language is created in the preceding code, and it takes two arguments called lang and year. Then we created the instance of the class Language, passed it the necessary arguments, and called the function data.
🌐
GeeksforGeeks
geeksforgeeks.org › python › __init__-in-python
__init__ in Python - GeeksforGeeks
class Dog: def __init__(self, name, breed="Mixed", age=1): self.name = name self.breed = breed self.age = age d1 = Dog("Buddy") d2 = Dog("Max", "Golden Retriever", 5) print(d1.name, d1.breed, d1.age) print(d2.name, d2.breed, d2.age) ...
Published   September 12, 2025
🌐
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
🌐
Index.dev
index.dev › blog › what-is-init-in-python
Master Python Objects: The Ultimate Guide to the __init__ Method
June 10, 2024 - For example, the dog object may have access to a walk() method in a dog class. This method is developed by the programmer, who then instructs it to execute specified tasks. Double underscores are used to distinguish special methods, such as __init__.
Find elsewhere
🌐
Sentry
sentry.io › sentry answers › python › `super()` and `__init__()` in python
`super()` and `__init__()` in Python | Sentry
July 15, 2023 - Consider the following code: MARKUP = 1.5 class Product: def __init__(self, name, cost_price): self.name = name self.cost_price = cost_price self.selling_price = cost_price * MARKUP class Perishable(Product): def __init__(self, name, cost_price, ...
🌐
C# Corner
c-sharpcorner.com › blogs › usage-of-init-and-self-in-python-classes
Usage of __init__ and Self in Python Classes
January 11, 2025 - class Employee: def __init__(self, name, department,paid): self.name = name self.department = department self.paid = paid def get_department(self): return self.department def get_PaidInfo(self): return self.paid obj = Employee("Ajay", "Sales", "Paid") print("Name of the Employee: "+obj.name) print("Department: "+obj.get_department()) print("Payment Status: "+obj....
🌐
Copahost
copahost.com › home › init python: learn how to use __init__ to initialize objects in python
init python: Learn how to use __init__ to initialize objects in python - Copahost
August 29, 2023 - We have a basic example of creating a Python class called “Person”. The class has a special method called “ init ” which is being called when we create an object of the class.
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)

🌐
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.
🌐
Real Python
realpython.com › python-class-constructor
Python Class Constructors: Control Your Object Instantiation – Real Python
January 19, 2025 - The process continues with the instance initializer, .__init__(), which takes the constructor’s arguments to initialize the newly created object. To explore how Python’s instantiation process works internally, consider the following example of a Point class that implements a custom version of both methods, .__new__() and .__init__(), for demonstration purposes:
🌐
iBiblio
ibiblio.org › g2swap › byteofpython › read › class-init.html
The __init__ method
#!/usr/bin/python # Filename: class_init.py class Person: def __init__(self, name): self.name = name def sayHi(self): print 'Hello, my name is', self.name p = Person('Swaroop') p.sayHi() # This short example can also be written as Person('Swaroop').sayHi()
🌐
Analytics Vidhya
analyticsvidhya.com › home › all about init in python
All About init in Python - Analytics Vidhya
February 1, 2024 - In the above example, the __init__ method of the “Circle” class initializes the instance variable “radius” with the value passed as an argument. Additionally, it calculates the area of the circle using the formula and assigns it to the ...
🌐
Python documentation
docs.python.org › 3 › tutorial › classes.html
9. Classes — Python 3.14.3 documentation
Just pretend that the class object ... the class. For example (assuming the above class): ... The instantiation operation (“calling” a class object) creates an empty object. Many classes like to create objects with instances customized to a specific initial state...
🌐
StrataScratch
stratascratch.com › blog › what-is-the-purpose-of-__init__-in-python
What Is the Purpose of __init__ in Python? - StrataScratch
November 7, 2024 - The __init__ method focuses on initializing that instance, allowing you to pass values that tailor its properties. In Python, the __init__ method is a class initializer. Before a new object is returned, it executes the __init__ method to initialize its state.
🌐
APXML
apxml.com › courses › python-for-beginners › chapter-8-introduction-object-oriented-concepts › python-init-method
Python __init__ Method | Class Constructor
For instance, if you have a Dog class, you probably want to specify the dog's name and breed right when you create a Dog object, rather than creating a generic dog and setting its attributes afterwards. Python provides a special method for this purpose: __init__.
🌐
Real Python
realpython.com › python-init-py
What Is Python's __init__.py For? – Real Python
July 9, 2025 - For example, say you want to add a package version number. A good spot for that would be inside of mediatools/__init__.py: ... You’d likely keep the other __init__.py files empty, although nothing prevents you from recording version information ...