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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With