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?
2 Answers 2
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 Comments
__init__ call those methods.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.
4 Comments
__init__ is called the constructor, but technically speaking, that's not correct. The constructor in Python is __new__, and __init__ is the initializer.__new__ is the one that is first called.__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.Constructor might be the most close thing to understand of what init does.
__new__()__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 thenBob.init_instance("Bob")will work.init_instanceinstead of__init__, but you can makeinit_instanceaclassmethodand calldog.init_instance('Bob')(changing it to also create an instance instead of just initializing one).