Python __init__ Method

Python The init() Method

The examples in the previous chapter were simple classes and objects. To understand the true meaning of Python classes, we have to understand the built-in __init__() function.

All classes have a function called __init__(), which is always executed when the class is being initiated (when an object is created). This function is known as a constructor in other programming languages.


Using the __init__() Function

Use the __init__() function to assign values to object properties, or to perform other operations that are necessary to do when the object is being created.

The __init__() Example

// Create a class named Person, use the __init__() function to assign values for name and age:
class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

p1 = Person("John", 36)

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

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


Default Parameter Values in __init__()

You can also provide default values for parameters in your __init__() method. If an object is created without passing those values, the defaults will be used.

Default Values Example

class Person:
  def __init__(self, name="Unknown", age=0):
    self.name = name
    self.age = age

// Uses the default values p1 = Person() print(p1.name) # Output: Unknown

// Overrides the default values p2 = Person("Alice", 28) print(p2.name) # Output: Alice


The __str__() Function

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

If the __str__() function is not set, the string representation of the object returns the memory address of the object, which isn't very readable.

The __str__() Example

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) # Output: John(36)


Exercise

?

When is the __init__() function executed in Python?