Defining the Beginning, End, and Behavior of Objects
In Python, a class is the blueprint for creating objects.
This lesson will cover constructors
, destructors
, and methods
, which are essential components of a class.
Defining the Beginning with a Constructor
A constructor
is a method that is automatically called when an object is created.
In Python, the constructor is defined using __init__
and it initializes the object's initial state.
class Car:
# Define the constructor
def __init__(self, brand, model, year):
# Set the attributes of the object
self.brand = brand
self.model = model
self.year = year
print(f"{self.brand} {self.model} created")
# Create a car object with brand 'Lamboo', model 'Avent', and year 2021
lambo = Car("Lamboo", "Avent", 2021)
# Output: Lamboo Avent created
# Create a car object with brand 'Tesla', model 'Model Z', and year 2023
tesla = Car("Tesla", "Model Z", 2023)
# Output: Tesla Model Z created
Through the __init__
code, every time a Car
object is created, the brand, model, and year of the car are set, and the brand and model are printed.
Defining the End with a Destructor
A destructor
is a method that is called when an object is destroyed.
In Python, it is defined using __del__
and is commonly used to perform clean-up tasks when an object is deleted.
class Car:
# Define the destructor
def __del__(self):
# Print when the object is destroyed
print(f"{self.brand} {self.model} is being destroyed")
Defining Behavior with Methods
A method
defines the behavior an object can perform.
Methods typically change the object's state or perform a specific action.
class Car:
def __init__(self, brand, model, year):
self.brand = brand
self.model = model
self.year = year
def start_engine(self):
print(f"Starting the engine of {self.brand} {self.model}")
def change_year(self, year):
self.year = year
print(f"The year of {self.brand} {self.model} has been changed to {year}")
# Create a car object with brand 'Lamboo', model 'Avent', and year 2021
lambo = Car("Lamboo", "Avent", 2021)
# Output: Starting the engine of Lamboo Avent
lambo.start_engine()
# Output: The year of Lamboo Avent has been changed to 2023
lambo.change_year(2023)
In the code above, the start_engine
method expresses the action of starting the car's engine, and the change_year
method changes the car's year.
The self
keyword included when defining methods refers to the instance of the object calling the method and must be included when defining methods.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.