Understanding Constructors and Class Variables in OOP
Classified in Computers
Written on in
English with a size of 3.89 KB
Constructor
A constructor is a special method in object-oriented programming that is automatically called when an instance (object) of a class is created. The main purpose of a constructor is to initialize the object's attributes (properties) and allocate resources if needed. Constructors have the same name as the class and do not have a return type.
Example of a Constructor
Here is an example in Python:
class Person:
def __init__(self):
self.name = "John Doe"
self.age = 30
# Creating an instance of the Person class
person = Person()
print(person.name) # Output: John Doe
print(person.age) # Output: 30
In this example, __init__ is the constructor method in the Person class. It initializes the name and age attributes of the... Continue reading "Understanding Constructors and Class Variables in OOP" »