मराठी
महाराष्ट्र राज्य शिक्षण मंडळएचएससी विज्ञान (संगणक विज्ञान) इयत्ता १२ वी

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×