B.Tech Students: Apply for Live Programming Internship C, C++, Java, Python ,Web page Designing, PHP Python Constructors | LiveCodeProgramming

Python Constructors (__init__ method)

Constructors are special methods used to initialize newly created objects. In Python, the constructor method is called __init__().

Constructor एक special method होता है जो object बनते समय automatically call होता है। Python में इसका नाम __init__() होता है।

Example 1: Basic Constructor
class Student:
    def __init__(self, name):
        self.name = name

s1 = Student('Aryan')
print(s1.name)

Output:

Aryan

Constructor initializes the 'name' property.

Constructor 'name' property को initialize करता है।

Example 2: Multiple Parameters
class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

s1 = Student('Naincy', 21)
print(s1.name, s1.age)

Output:

Naincy 21

Multiple attributes are set in constructor.

Constructor में एक से अधिक attribute सेट किए जाते हैं।