Special method __init__ #
We can create a method for a class by defining a function inside the class body. A method is a function defined within a class that can be called just like a regular function.
For example:
class Car:
def method_name(self):
print("The method method_name is called")
car = Car()
car.method_name() # Output: The method method_name is called
self. This value is automatically passed to the method whenever it is called, and we do not need to pass it ourselves.
In the example above, the self value will be the object car.
What is the __init__ method #
The __init__ method in Python is a special method, also known as the constructor method, which gets automatically called when an object is created from a class.
For example, if we update the Car class to have the __init__ method, like so:
class Car
def __init__(self):
print("A new car object is created")
car = Car() # Output: A new car is created
car2 = Car() # Output: A new car is created
Whenever we create a new car object with Car(), the method __init__ is then called. In this case, the message "A new car object is created" is then printed in the output.
Exercise #
- Create an
__init__method inside outPersonclass that prints out a message whenever an object is created from thePersonclass. Then try creating an object from thePersonclass.
Tests #
- The message
"A new person is created"should be printed when a newPersonobject is created - Variable
new_personshould be aPersonobject
Getting Started with Python
Data Types
Python Functions
Statements in Python
Basic Debugging in Python
Basic Algorithm
Object-Oriented Programming
Error Handling
Intermediate Algorithm
Python Modules