Write a Python class with an __init__ method and show what happens when you call it directly.
__init__ is the initialiser. The interpreter calls it automatically once the object has been created, and its job is to set the initial state of that object.
class Rectangle:
def __init__(self, width, height):
if width <= 0 or height <= 0:
raise ValueError('dimensions must be positive')
self.width = width
self.height = height
def area(self):
return self.width * self.height
rect = Rectangle(3, 4)
print(rect.area())
# __init__ is an ordinary method, so it can be called directly.
Rectangle.__init__(rect, 5, 6)
print(rect.area())
Calling Rectangle(3, 4) creates the object and then runs __init__ on it. The method itself returns None, because its job is the side effect of setting the attributes. The object comes from the call to the class and not from the return value of __init__.
The last two lines show that __init__ is an ordinary method and not a special hook that only the interpreter can trigger. Calling it directly on an object that already exists re-initialises that object, which works but is rarely what you want. In normal code you would simply assign the attributes again instead.
There are two rules about the signature. It must return None, and if you define it then you should always accept self as the first parameter. There is also no automatic return value anywhere in the process. A class without an __init__ gets a default one that accepts no arguments at all, which is why Rectangle() with no arguments raises a TypeError instead of quietly creating an empty object.