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.
__init__() FunctionUse 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.
// 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.
__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.
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
__str__() FunctionThe __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.
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)
When is the __init__() function executed in Python?