5

I am relativly new to python and I was wondering if you could create an instance of a class without defining the init explicity. Could I call it something else?

First example - with the init method:

class dog:
def __init__(self,name):
 self.name=name
 print('My name is',name)
Bob = dog('Bob')

Second example - without the init method:

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

In the first example the code works but in the second example I get:

TypeError: object() takes no parameters

So based on this I assume that one has to explicitly call the init method. BUT I have seen code where the init method has not been used, how come?

asked Dec 9, 2017 at 10:25
6
  • 1
    Check out __new__() Commented Dec 9, 2017 at 10:28
  • When creating an object from class the parameters you pass are passed to the __init__ function declared in the class. Since you have not declared it, python will fall back to the default implementation which does not accept any arguments. Bob = dog() and then Bob.init_instance("Bob") will work. Commented Dec 9, 2017 at 10:29
  • Well, Python isn’t going to know that it should call something named init_instance instead of __init__, but you can make init_instance a classmethod and call dog.init_instance('Bob') (changing it to also create an instance instead of just initializing one). Commented Dec 9, 2017 at 10:30
  • 1
    Maybe if you said why you are trying to do this, you would get better help. Commented Dec 9, 2017 at 10:34
  • 2
    @Anake I am not trying to do anything, just trying to understand why I explicity need to call __init__(). Why I cant name it someting else. Commented Dec 9, 2017 at 10:36

2 Answers 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.

answered Dec 9, 2017 at 10:35
Sign up to request clarification or add additional context in comments.

2 Comments

This was a good explanation, finally. So I want to summarize how it works when creating an object: __new__() creates the instance __init__() initalize the instance, i.e. preparing my object to have e.g. names, colors etc. But we can make our own initializer and call it instead.
@John Correct. In fact, with large classes (eg for a GUI), it's common to break up the initialization into separate logical stages, with a separate method for each stage, and have __init__ call those methods.
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.

answered Dec 9, 2017 at 10:38

4 Comments

Sometimes __init__ is called the constructor, but technically speaking, that's not correct. The constructor in Python is __new__, and __init__ is the initializer.
Technically both are used to construct objects, but talking about priorities, __new__ is the one that is first called.
Well sure, because __init__ (usually) constructs the instance attributes. OTOH, a lot of terminology used to describe the mechanics of other languages doesn't really apply well to Python because Python doesn't have declarations, it just defines things.
That's true, I just thought if the OP is coming from a different programming background Constructor might be the most close thing to understand of what init does.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.