def __init__(self, items=None):
    if items is None: items = []
    self.l = items

In response to @Eastsun's edit, I propose a different structure to __init__

def __init__(self, items=()):
    ''' Accepts any iterable 
    The appropriate TypeError will be raised if items is not iterable '''
    self.l = list(items)

Note that lowercase l is a bad name, it can be confused with 1

Answer from jamylak on Stack Overflow
🌐
Reddit
reddit.com › r/learnpython › creating instances in classes with __init__ method and without
r/learnpython on Reddit: Creating instances in classes with __init__ method and without
April 8, 2024 -

Hello everyone!

While learning about classes in Python, I encountered the following two questions. Consider the following two classes:

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

and

class Dog:
    def dog_constructor(self, name, age):
        self.name = name
        self.age = age

The main difference is that the first class contains an __init__ method, but the second one does not.

To create an instance in the first class, I used: my_dog = Dog('Willie', 5). However,

for the second one I tried: my_dog = Dog.dog_constructor('Willie', 10) which did not work. Then eventually

I was told that I should use

my_dog = Dog()
my_dog.dog_constructor('Willie', 5).

I am so confused about why we should use this approach.

Can anyone explain to me the importance of having an __init__ method in a class and why instances are created differently depending on whether we have __init__ or not?

I have been struggling with this for a while but still cannot grasp it.

I'd be very thankful for the explanation! Thank you!

Top answer
1 of 5
4
Methods that start and end with a double underscore are called "dunders" or "magic methods". Python looks for these specific names in some situations. When you create a new class object, one of python's syntactic sugars is that it automatically runs __init__ (if it exists). my_dog = Dog() my_dog.__init__() # python will automatically run this and not tell you Python has many little secrets like this, that you will learn over time. These little shortcuts are what make python so user friendly and fast to program.
2 of 5
2
You were hit by at least two issues. 1. Doing or returning? You need to discern between methods, which do something to your class instance, and methods, which return something from your class instance. In your case, dog_constructor() is a method, which does something: It puts values into your object. But it doesn't return anything. Or rather: Any function or method, which doesn't return anything in your code, will return None, because Python will do that automatically for you. So even if the line below had worked, the right side of '=' would have returned None, and consequently my_dog would have ended up being None: my_dog = Dog.dog_constructor('Willie', 10) 2. You need a class instance, not a class In this line, you call a method of the Dog class. You don't call a method of an instance of Dog. my_dog = Dog.dog_constructor('Willie', 10) When you run this, Python will still attempt to run the dog_constructor() method. But because it is called directly on the class, not an instance, there will be no 'self' to send to the method. So Python will send your two input arguments, 'Willie' and 5, to dog_constructor, and dog_constructor will think that 'Willie' should go into 'self', and 5 should go into 'name'. And then there is no arguments left, so you get an error that the argument 'age' is missing. You could have created an instance of Dog on the fly by adding '()', and then dog_constructor() would have been called as an instance of that instance: my_dog = Dog().dog_constructor('Willie', 10) Here Python will create an instance of Dog, and call the method on that instance. But the variable 'my_dog' gets assigned to the output from dog_constructor(), which is None. So when the line has finished running, your new object disappears into nothing because there is no variable assigned to it. Now let us look at the example from your post, which actually worked: my_dog = Dog() my_dog.dog_constructor('Willie', 10) The first line creates a new instance of Dog. And the my_dog variable gets assigned to that instance. So now you have both an object, and a variable, which is tied to that object. This will last, also after the line has finished running. The next line will fill data into your object, and this will happen as inplace modifications. Nothing is returned, but your object will remember these modifications. (I should add, that you can change your constructor method, so it will create a new object instance and return it. But this post is probably already confusing enough, so I will stop here.)
Discussions

class - Python Classes without using def __init__(self) - Stack Overflow
I am writing a series of text menus. With the class and sub class below it runs with no issues. But I am reviewing my coding and I am wondering....is it ok that I didn't use def __init__(self) in the More on stackoverflow.com
🌐 stackoverflow.com
Python inheritance: TypeError: object.__init__() takes no parameters - Stack Overflow
I get this error: TypeError: object.__init__() takes no parameters when running my code, I don't really see what I'm doing wrong here though: class IRCReplyModule(object): activated=True More on stackoverflow.com
🌐 stackoverflow.com
April 29, 2019
How do I pass __init__ arguments to a subclass without repeating them?
Another solution - use dataclasses, which will write the constructors for you. from dataclasses import dataclass @dataclass class Modifier: value: str name: str hidden: str = 'yes' # Why not a bool?! generate_add_modifiers: str = '(produces)' @dataclass class Derived(Modifier): is_position: bool = false # You can't get away without a default $ help(dataclass_test2.Derived.__init__) Help on function __init__ in module dataclass_test2: __init__(self, value: str, name: str, hidden: str = 'yes', generate_add_modifiers: str = '(produces)', is_position: bool = False) -> None More on reddit.com
🌐 r/learnpython
33
124
July 18, 2021
python - using __init__ method with and without parameters - Stack Overflow
I am new in python and please excuse me if my question is a basic question or is not clear. I have a class in python and I want to set some attributes for my objects whenever I generate my object... More on stackoverflow.com
🌐 stackoverflow.com
People also ask

What is __init__ in Python?
A special method Python calls automatically when you create an object, used to set its initial attributes. You never call it directly: instantiating the class runs it, with the arguments you passed.
🌐
copahost.com
copahost.com › home › init in python: how object initialisation works
init python: Learn how to use __init__ to initialize objects in ...
Is __init__ a constructor in Python?
Not strictly. The __new__ method creates the object and __init__ initialises it, so by the time __init__ runs the object already exists. In practice the distinction rarely matters, because you will almost never write __new__.
🌐
copahost.com
copahost.com › home › init in python: how object initialisation works
init python: Learn how to use __init__ to initialize objects in ...
Can __init__ return a value in Python?
No. It must return None, and anything else raises TypeError. A bare return to exit early is allowed; returning a value is not.
🌐
copahost.com
copahost.com › home › init in python: how object initialisation works
init python: Learn how to use __init__ to initialize objects in ...
Top answer
1 of 6
87

You can circumvent __init__ by calling __new__ directly. Then you can create a object of the given type and call an alternative method for __init__. This is something that pickle would do.

However, first I'd like to stress very much that it is something that you shouldn't do and whatever you're trying to achieve, there are better ways to do it, some of which have been mentioned in the other answers. In particular, it's a bad idea to skip calling __init__.

When objects are created, more or less this happens:

a = A.__new__(A, *args, **kwargs)
a.__init__(*args, **kwargs)

You could skip the second step.

Here's why you shouldn't do this: The purpose of __init__ is to initialize the object, fill in all the fields and ensure that the __init__ methods of the parent classes are also called. With pickle it is an exception because it tries to store all the data associated with the object (including any fields/instance variables that are set for the object), and so anything that was set by __init__ the previous time would be restored by pickle, there's no need to call it again.

If you skip __init__ and use an alternative initializer, you'd have a sort of a code duplication - there would be two places where the instance variables are filled in, and it's easy to miss one of them in one of the initializers or accidentally make the two fill the fields act differently. This gives the possibility of subtle bugs that aren't that trivial to trace (you'd have to know which initializer was called), and the code will be more difficult to maintain. Not to mention that you'd be in an even bigger mess if you're using inheritance - the problems will go up the inheritance chain, because you'd have to use this alternative initializer everywhere up the chain.

Also by doing so you'd be more or less overriding Python's instance creation and making your own. Python already does that for you pretty well, no need to go reinventing it and it will confuse people using your code.

Here's what to best do instead: Use a single __init__ method that is to be called for all possible instantiations of the class that initializes all instance variables properly. For different modes of initialization use either of the two approaches:

  1. Support different signatures for __init__ that handle your cases by using optional arguments.
  2. Create several class methods that serve as alternative constructors. Make sure they all create instances of the class in the normal way (i.e. calling __init__), as shown by Roman Bodnarchuk, while performing additional work or whatever. It's best if they pass all the data to the class (and __init__ handles it), but if that's impossible or inconvenient, you can set some instance variables after the instance was created and __init__ is done initializing.

If __init__ has an optional step (e.g. like processing that data argument, although you'd have to be more specific), you can either make it an optional argument or make a normal method that does the processing... or both.

2 of 6
26

Use classmethod decorator for your Load method:

class B(object):    
    def __init__(self, name, data):
        self._Name = name
        #store data

    @classmethod
    def Load(cls, file, newName):
        f = open(file, "rb")
        s = pickle.load(f)
        f.close()

        return cls(newName, s)

So you can do:

loaded_obj = B.Load('filename.txt', 'foo')

Edit:

Anyway, if you still want to omit __init__ method, try __new__:

>>> class A(object):
...     def __init__(self):
...             print '__init__'
...
>>> A()
__init__
<__main__.A object at 0x800f1f710>
>>> a = A.__new__(A)
>>> a
<__main__.A object at 0x800f1fd50>
🌐
AskPython
askpython.com › python › oops › python-class-constructor-init-function
Python Class Constructor - Python __init__() Function - AskPython
October 10, 2019 - The object class is the base of ... = i class Data(BaseData): pass d = Data(10) print(type(d)) ... We can create a constructor without any arguments....
🌐
Linux Hint
linuxhint.com › init-function-python-2
Use of the __init__() Function in Python – Linux Hint
This function will be called when the object of the TestClass will be created. #Declare a class with parameterless constructor class TestClass: #Declare constructor method def __init__(self): #Print a simple message print('Constructor method has been called.') #Create object of the class object ...
Find elsewhere
🌐
Quora
quora.com › How-do-I-create-a-constructor-without-arguments-in-python
How to create a constructor without arguments in python - Quora
Answer (1 of 2): If you need to make some or all of the arguments to the constructor optional, initialize them to None: [code]class MyClassyClassWithSomeSass(object): def __init__(self, arg1=None, arg2=None): self.__arg1 = arg1 self.__arg2 = arg2 [/code]
🌐
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__ method created without passing parameters is called the default __init__ constructor. When we call a function using (), in actuality, the __call__ method is implemented in the function.
🌐
Copahost
copahost.com › home › init in python: how object initialisation works
init python: Learn how to use __init__ to initialize objects in ...
August 29, 2023 - A special method Python calls ... set its initial attributes. You never call it directly — instantiating the class runs it, with the arguments you passed. ... Because self is the object being worked on, and Python passes it as the first argument automatically. Without a parameter to receive ...
🌐
Quora
quora.com › What-happens-if-you-define-a-python-class-without-an-__init__-function
What happens if you define a python class without an __init__ function? - Quora
Instances of a class almost always have instance variables, and they need to be created in __init__ to ensure that every instance automatically has them. ... Your website. No coding required. No coding needed. WordPress.com gives you everything to build, grow, and own your site. ... If a Python ...
🌐
Great Learning
mygreatlearning.com › blog › it/software development › python __init__: an overview
Python __init__: An Overview
October 14, 2024 - The python __init__ method is declared within a class and is used to initialize the attributes of an object as soon as the object is formed. While giving the definition for an __init__(self) method, a default parameter, named ‘self’ is always passed in its argument.
Top answer
1 of 2
126

You are calling the wrong class name in your super() call:

class SimpleHelloWorld(IRCReplyModule):

     def __init__(self):
            #super(IRCReplyModule,self).__init__('hello world')
            super(SimpleHelloWorld,self).__init__('hello world')

Essentially what you are resolving to is the __init__ of the object base class which takes no params.

Its a bit redundant, I know, to have to specify the class that you are already inside of, which is why in python3 you can just do: super().__init__()

2 of 2
5

This has bitten me twice recently (I know I should have learned from my mistake the first time) and the accepted answer hasn't helped me either time so while it is fresh in my mind I thought I would submit my own answer just in case anybody else is running into this (or I need this again in future).

In my case the issue was that I was passing a kwarg into the initialisation of the subclass but in the superclass that keyword arg was then being passed though into the super() call.

I always think these types of things are best with an example:

class Foo(object):
  def __init__(self, required_param_1, *args, **kwargs):
    super(Foo, self).__init__(*args, **kwargs)
    self.required_param = required_param_1
    self.some_named_optional_param = kwargs.pop('named_optional_param', None)

  def some_other_method(self):
    raise NotImplementedException

class Bar(Foo):
  def some_other_method(self):
    print('Do some magic')


Bar(42) # no error
Bar(42, named_optional_param={'xyz': 123}) # raises TypeError: object.__init__() takes no parameters

So to resolve this I just need to alter the order that I do things in the Foo.__init__ method; e.g.:

class Foo(object):
  def __init__(self, required_param_1, *args, **kwargs):
    self.some_named_optional_param = kwargs.pop('named_optional_param', None)
    # call super only AFTER poping the kwargs
    super(Foo, self).__init__(*args, **kwargs)
    self.required_param = required_param_1
🌐
W3Schools
w3schools.com › python › python_class_init.asp
Python __init__() Method
All classes have a built-in method called __init__(), which is always executed when the class is being initiated.
🌐
Reddit
reddit.com › r/learnpython › how do i pass __init__ arguments to a subclass without repeating them?
r/learnpython on Reddit: How do I pass __init__ arguments to a subclass without repeating them?
July 18, 2021 -
class Modifier:

    def __init__(self, value, name):
        self.value = value
        self.name = name
        self.hidden = "yes"
        self.generate_add_modifiers = "{produces}"

    def generate_script(self):
        script = f"""{{
            #value = {self.value}
            #name = {self.name}
            hidden = {self.hidden}
            generate_add_modifiers = {self.generate_add_modifiers}
        }}"""
        return script


class DerivedModifier(Modifier):
    def __init__(self, is_positive):
        self.is_positive = is_positive

The above code is part of a game scripting language generator I'm working on. I've not dealt much with classes, but I assumed that arguments from a parents init method would get passed to it's childs init automatically.

However, pycharm is complaining about invalid arguments when I try to do the following:

m = DerivedModifier(name = Test, value = "50", is_positive = "True")

Is this not the case? How can I achieve this without repeating myself?

🌐
Real Python
realpython.com › python-class-constructor
Python Class Constructors: Control Your Object Instantiation – Real Python
October 21, 2025 - As you learned before, .__init__() runs the second step of the object instantiation process in Python. Its first argument, self, holds the new instance that results from calling .__new__(). The rest of the arguments to .__init__() are normally used to initialize instance attributes. In the above example, you initialized the rectangle’s .width and .height using the width and height arguments to .__init__(). It’s important to note that, without counting self, the arguments to .__init__() are the same ones that you passed in the call to the class constructor.
Top answer
1 of 2
8

Every class has an __init__ method. If it doesn't explicitly define one, then it will inherit one from its parent class. In your 2nd example, the class inherits __init__ and a bunch of other methods (and other non-method attributes) from the base object class. We can see that via the dir function:

class Dog:
    def init_instance(self,name):
        self.name = name
        print('My name is',name)

print(dir(Dog))

output

['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'init_instance']

__init__ gets called automatically after the instance is constructed (via the __new__ method), so we might as well use it if we need to initialize our instance. But we can call your init_instance explicitly:

bob = Dog()
bob.init_instance('Bob')
print(bob.name)    

output

My name is Bob
Bob

If you give you class an initializer that isn't named __init__ then it won't get called automatically. How should Python know that that method is an initializer? Although it's customary to make __init__ the first method in the class definition, that's by no means mandatory, and some people like to put __init__ last.

You said: "I have seen code where the init method has not been used, how come?" Well, some classes simply don't need their instances to be initialized: their instance attributes are set via various other methods, or by direct assignment in code outside the class definition, eg bob.color = 'brown'. Or they inherit a perfectly usable __init__ from a parent class.

2 of 2
1

init is nothing else then a method to initially prepare the state of your object. In other languages they have similar concepts as Constructors and it's not necessarily needed.

🌐
BeginnersBook
beginnersbook.com › 2018 › 03 › python-constructors-default-and-parameterized
Python Constructors – default and parameterized
March 10, 2018 - Example: When we declare a constructor In this case, python does not create a constructor in our program. class DemoClass: num = 101 # non-parameterized constructor def __init__(self): self.num = 999 # a method def read_number(self): print(self.num) # creating object of the class obj = DemoClass() # calling the instance method using the object obj obj.read_number()