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 runs automatically when an object is created from a class. 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.
Lessons in this chapter · Basics of Object-Oriented Programming - Classes, Instances, Attributes, Methods
- 1. Introduction to Object-Oriented Programming (OOP)
- 2. Everything About Python - What is an Object?
- 3. Relationship Between Class and Instance
- 4. How to Declare a Class in Python
- 5. What is a Class Constructor?
- 6. The Relationship Between Classes and Methods
- 7. Multiple-choice quiz
- 8. Inheritance of Class Attributes and Methods
- 9. How to Bundle Attributes and Methods with Encapsulation
- 10. Adding Flexibility to Objects with Polymorphism
- 11. Coding Quiz - Creating a Car Class
- 12. Multiple-choice quiz
- 13. Fill-in-the-blank quiz
Which method is used to define a constructor for a class in Python?
__start__
__create__
__init__
__begin__
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help