Posts

Showing posts with the label Python Constructor

Python Constructor (__init__) Explained for Beginners with Examples

Python Constructor (__init__) Explained for Beginners Python Constructor (__init__) Explained for Beginners Introduction In the previous post, we learned about Python Classes and Objects . Now we will learn about an important concept in OOP called a Constructor . A constructor is a special method used to initialize object values when an object is created. --- What is a Constructor? A constructor is a special function that automatically runs when an object is created from a class. In Python, the constructor method is called: __init__() --- Basic Example class Student: def __init__(self): print("Constructor is called") s1 = Student() When the object s1 is created, the constructor runs automatically. --- Constructor with Parameters We usually use constructors to assign values to object variables. class Student: def __init__(self, name, age): self.name = name self.age = age s1 = Student(...