SwadhyAI Notes

All Python notes

Python __init__() Function 🚀

The __init__() Function

The examples above are classes and objects in their simplest form, and are not really useful in real life applications. To understand the meaning of classes we have to understand the built-in __init__() function.

✨ Initialization

All classes have a function called __init__(), which is always executed when the class is being initiated. Use the __init__() function to assign values to object properties, or other operations that are necessary to do when the object is being created:

python
class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

p1 = Person("John", 36)

print(p1.name)
print(p1.age)

🔄 The __str__() Function

The __str__() function controls what should be returned when the class object is represented as a string.

python
class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

  def __str__(self):
    return f"{self.name}({self.age})"

p1 = Person("John", 36)

print(p1)

💡 Did You Know?

The __init__() function is called automatically every time the class is being used to create a new object.