Python Constructor and Initialisation

Learn about __new__ and __init__ in Python

Image for post
Image for post
Photo by Pablo Merchán Montes on Unsplash

JavaScript

class Polygon {
constructor() {
this.name = ‘Polygon’;
}
}
const poly1 = new Polygon();console.log(poly1.name);
// expected output: “Polygon”

Python __new__ vs. __init__

class Polygon():
def __init__(self, area):
self.area = area
poly1 = Polygon(20)
class Polygon():
def __init__(self, area):
self.area = area
class Square(Polygon):
def __init__(self, area):
super().__init__(area)
square1 = Square(10)print(Square.__mro__)
print(Square.__new__ is Polygon.__new__)
print(Square.__new__ is object.__new__)
====================>
(<class '__main__.Square'>, <class '__main__.Polygon'>, <class 'object'>)
True
True
class Polygon:
def __new__(cls):
print (f"construct {cls}")
return object.__new__(cls)
poly1 = Polygon()===============>
construct <class '__main__.Polygon'>
class ModularTuple(tuple):
def __new__(cls, tup, times=3):
tup = (int(x) * times for x in tup)
return super(ModularTuple, cls).__new__(cls, tup)
mt = ModularTuple((1,2,3))print(mt)
print(tuple.__new__ is ModularTuple.__new__)
======================>
(3, 6, 9)
True

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store