Interview question
What are constructors and destructors in Python? Python में constructors और destructors क्या हैं?
Answer
class Person:
def __init__(self, name, age):
print('Constructor called')
self.name = name
self.age = age
def __del__(self):
print(f'Destructor called for {self.name}')
# Constructor is called when object is created
person = Person('John', 30) # Constructor called
del person # Destructor called
# init vs new
class MyClass:
def __new__(cls):
print('__new__ called - create instance')
return super().__new__(cls)
def __init__(self):
print('__init__ called - initialize instance')
obj = MyClass()
# Output:
# __new__ called - create instance
# __init__ called - initialize instancedef __init__(self): # Constructor
print('Object created')
def __del__(self): # Destructor
print('Object deleted')
# Constructor object create होने पर call होता है
# Destructor object delete होने पर call होता हैWas this answer clear?