Python Constructor and Initialisation

Learn about __new__ and __init__ in Python

Photo by Pablo Merchán Montes on Unsplash

JavaScript

In JavaScript, the constructor method is a syntax sugar method of a class for creating and initialising an object of that class. And class is another syntax sugar for a type of function.

class Polygon {
constructor() {
this.name = ‘Polygon’;
}
}
const poly1 = new Polygon();console.log(poly1.name);
// expected output: “Polygon”
  • It creates __proto__ on poly1 and makes it point to Polygon.prototype so poly1.__proto__ === Polygon.prototype
  • It executes poly1.prototype.constructor (which is definition of function Polygon ) with the newly created empty object as its context (this), so the name property gets added to newly created object.
  • It returns newly created object

Python __new__ vs. __init__

class Polygon():
def __init__(self, area):
self.area = area
poly1 = Polygon(20)
  • An instance of Polygon is created aka poly1 and the __init__ method is invoked on the instancepoly1 object.__new__(self, *args, **kwargs) aka. object.__new__(poly1, area=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

Hi :)