हिंदी

Explain Constructor with an example. - Computer Science 1

Advertisements
Advertisements

प्रश्न

Explain Constructor with an example.

स्पष्ट कीजिए
Advertisements

उत्तर

A constructor is a specialised method within a class that is automatically called the moment an object is created. Its main job is to "set up" the object by assigning initial values to its data members.

Example:

class Car:
    # This is the constructor
    def __init__(self, brand, year):
        self.brand = brand  # Initializing the brand attribute
        self.year = year    # Initializing the year attribute

# Creating an object triggers the constructor automatically
my_car = Car("Toyota", 2022)

print(my_car.brand) # Output: Toyota
shaalaa.com
  क्या इस प्रश्न या उत्तर में कोई त्रुटि है?
2023-2024 (July) Official Board Paper

APPEARS IN

Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×