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.

Answer from Rosh Oxymoron on Stack Overflow
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>
🌐
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.)
Top answer
1 of 4
64

When feasible, letting __init__ get called (and make the call innocuous by suitable arguments) is preferable. However, should that require too much of a contortion, you do have an alternative, as long as you avoid the disastrous choice of using old-style classes (there is no good reason to use old-style classes in new code, and several good reasons not to)...:

   class String(object):
      ...

   bare_s = String.__new__(String)

This idiom is generally used in classmethods which are meant to work as "alternative constructors", so you'll usually see it used in ways such as...:

@classmethod 
def makeit(cls):
    self = cls.__new__(cls)
    # etc etc, then
    return self

(this way the classmethod will properly be inherited and generate subclass instances when called on a subclass rather than on the base class).

2 of 4
15

A trick the standard pickle and copy modules use is to create an empty class, instantiate the object using that, and then assign that instance's __class__ to the "real" class. e.g.

>>> class MyClass(object):
...     init = False
...     def __init__(self):
...         print 'init called!'
...         self.init = True
...     def hello(self):
...         print 'hello world!'
... 
>>> class Empty(object):
...     pass
... 
>>> a = MyClass()
init called!
>>> a.hello()
hello world!
>>> print a.init
True
>>> b = Empty()
>>> b.__class__ = MyClass
>>> b.hello()
hello world!
>>> print b.init
False

But note, this approach is very rarely necessary. Bypassing the __init__ can have some unexpected side effects, especially if you're not familiar with the original class, so make sure you know what you're doing.

🌐
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
If your class without __init__ uses inheritance then the __init__ of the superclass is called automatically whe. You try to create an instance; and since everything ultimately inherits from object, that means even my empty class will call object.__init__; a method that effectively does nothing.
🌐
CSDN
devpress.csdn.net › python › 63045285c67703293080b15f.html
How to create a class instance without calling initializer?_python_Mangs-Python
August 23, 2022 - #! /usr/bin/env python3 METHOD = 'metaclass' class NoInitMeta(type): def new(cls): return cls.__new__(cls) class String(metaclass=NoInitMeta if METHOD == 'metaclass' else type): def __init__(self, value): self.__value = tuple(value.split()) self.__alpha = tuple(filter(None, ( ''.join(c for c in word.casefold() if 'a' <= c <= 'z') for word in self.__value))) def __str__(self): return ' '.join(self.__value) def __eq__(self, other): if not isinstance(other, type(self)): return NotImplemented return self.__alpha == other.__alpha if METHOD == 'metaclass': def __getitem__(self, key): if not isinstan
🌐
Reddit
reddit.com › r/learnpython › how this becomes class created without __init__
r/learnpython on Reddit: How this becomes class created without __init__
September 1, 2025 - Possibly the internals have a default, and anything in code is overriding that ... In Python, __init__ is optional as it is not a traditional constructor - the object is already created before __init__ is called.
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.

Find elsewhere
🌐
Narkive
comp.lang.python.narkive.com › ILkg4iD1 › how-to-create-instances-of-classes-without-calling-the-constructor
how to create instances of classes without calling the constructor?
But you can create a new instance without calling the initialiser __init__. Here's a variation on a recipe from Alex Martelli: class Spam(object): def __init__(self, *args): print "spam spam spam spam" self.args = args def empty_instance(cls): class Empty(cls): def __init__(self): pass x = Empty() x.__class__ = cls return x
🌐
Stack Overflow
stackoverflow.com › questions › 41836939 › how-to-create-an-object-in-python-without-using-init
How to create an object in python without using __init__ - Stack Overflow
So for this piece of code class CircleT: def __init__(self,x,y,r): self.x = x self.y = y self.r = r Lets say I want to create a CircleT object named Circle1. I would...
🌐
Quora
quora.com › Is-it-possible-to-initialize-objects-without-explicitly-creating-them-using-classes-in-Python
Is it possible to initialize objects without explicitly creating them using classes in Python? - Quora
Answer (1 of 2): If you don't create them, they don't exist. But the process of initialization involves creating them. You go to a bank, you can't deposit if your savings account has not been created. They cannot initialize it with an initial deposit. Creating means allocating physical memory to ...
🌐
Python Forum
python-forum.io › thread-34797.html
Not including a constructor __init__ in the class definition...
September 1, 2021 - Hello Forum, We can create a class and include, at the very beginning, the __init__ special method called the constructor which can be parametrized or not. The __init__ method is called anytime an obj
🌐
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.
🌐
DEV Community
dev.to › delta456 › python-init-is-not-a-constructor-12on
Python: __init__() is not the only constructor - DEV Community
February 8, 2020 - In everyday Python programming, we just override the __init__ method to assign values to the object that was already created earlier by the default __new__ behaviour. __init__ is not the constructor, since it receives a pre-created instance ...
🌐
Python.org
discuss.python.org › python help
Confused about calling a method on a class without instantiating the object - Python Help - Discussions on Python.org
December 10, 2022 - Hello all, sorry for the funky title, I didn’t know how to sum up the question. So I’m learning how to use tkinter and in a few of the code examples I’m seeing the following pattern: import tkinter from tkinter import ttk root = tkinter.Tk() ttk.Button(root, text='Hello World').grid() root.mainloop() ttk.Button is a class and grid() is one if it’s methods; grid() renders a button symbolized by the ttk.Button class to the window symbolized by the tkinter.Tk object root What I don’t understan...
🌐
CodeQL
codeql.github.com › codeql-query-help › python › py-missing-call-to-init
Missing call to superclass __init__ during object initialization — CodeQL query help documentation
If the __init__ method of a superclass is not called during object initialization, this can lead to errors due to the object not being fully initialized, such as having missing attributes.