What do __init__ and self do in Python?
__init__
is a special method in Python classes, also known as a constructor. It is used to initialize the attributes of an object when it is created. The self
parameter refers to the instance of the object itself, and is used to access the attributes and methods of the class.
Here is an example of a simple class definition with an __init__
method:
class MyClass:
def __init__(self, value):
self.value = value
obj = MyClass(5)
print(obj.value) # Output: 5
In this example, when an object of the MyClass
is created, the __init__
method is called and the value of the value
attribute is set to the argument passed to the constructor (in this case, 5). The self
parameter is used to refer to the instance of the object, so self.value
sets the value
attribute on obj
.