Constructors are special methods that are automatically called when an object is created.
1.1 The __init__ Method
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
print(f"{name} created!")
p = Person("Alice", 30) # Alice created!
1.2 The __new__ Method
class Singleton:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
s1 = Singleton()
s2 = Singleton()
print(s1 is s2) # True