Jul 18, 2024
__init____new____call__ special method makes an instance callable__new__ method__init__ methodclass SomeClass:
pass
instance = SomeClass()
class Point:
def __new__(cls, *args, **kwargs):
instance = super().__new__(cls)
return instance
def __init__(self, x, y):
self.x = x
self.y = y
__new__ creates object, __init__ initializes x and y__init____init__class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
__init__
class Rectangle:
def __init__(self, width, height):
if width <= 0 or height <= 0:
raise ValueError("Width and height must be positive")
self.width = width
self.height = height
super() in Subclasses__init__
class Person:
def __init__(self, name, birthdate):
self.name = name
self.birthdate = birthdate
class Employee(Person):
def __init__(self, name, birthdate, position):
super().__init__(name, birthdate)
self.position = position
__init__class Greeter:
def __init__(self, name, formal=False):
self.name = name
self.formal = formal
def greet(self):
greeting = "Hello, " if self.formal else "Hi, "
return f"{greeting}{self.name}"
__new__