What is a Class Constructor?
In this lesson, we will delve deeper into the class constructor
that we have previously learned about.
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 creating an object, the attributes of the object are initialized with the arguments passed to the __init__
method, and the object's information is printed through the get_product_info
method.
Which method is used to define a constructor for a class in Python?
__start__
__create__
__init__
__begin__
Guidelines
AI Tutor
Publish
Design
Upload
Notes
Favorites
Help
Code Editor
Execution Result