What is a Class Constructor?
In this lesson, we will gain a deeper understanding of the class constructor
,building on what we previously learned.
A constructor
is a special method that is automatically called when an object is created from a class, and it sets the initial state of the object.
In Python, a constructor is defined as __init__
, which stands for Initialization
, and it is referred to as the constructor method
or initialization method
.
The self
used as the first argument in the __init__
method refers to the current instance of the class.
Notice that there are two underscores (_
) before and after init
, making a total of four underscores.
class Product:
def __init__(self, name, category, price):
self.name = name # Product name
self.category = category # Product category
self.price = price # Price
def get_product_info(self):
return f"{self.category}: {self.name} - ${self.price}"
# Creating an object and printing information
product1 = Product("Earphones", "Electronics", 85)
print(product1.get_product_info())
# Electronics: Earphones - $85
The code example above defines the Product
class and initializes the product name (name
), product category (category
), and price (price
) through the __init__
method.
The get_product_info
method returns the product information as a string using the attributes of the object.
When an object is created, its attributes are initialized with the arguments passed to the __init__
method, and its information is printed using the get_product_info
method.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.