Super().__new__(cls)

Hi I am having difficulty understanding __new__

class TestA:
	def __new__(cls, value):
		instance = super().__new__(cls)
		return instance
	def __init__(self, value):
		self.value = value
x = TestA(1)
x #__main__.TestA object

class TestB:
	def __new__(cls, value):
		return cls(value)
	def __init__(self, value):
		self.value = value
x = TestB(1) #RecursionError
class TestC:
	def __new__(cls, value):
		return cls
	def __init__(self, value):
		self.value = value
x = TestC(1)
x #<class '__main__.TestC'>

So my questions are:

  1. How and why super().__new__(cls) initialize the class and returns an object?
  2. Why super().__new__(cls) doesn’t take arguments except cls and TestA.__new__(TestA, 1) does take an argument (value)?

magic methods (like __new__ and __init__) are called at a certain point, __new__ is called when we create a new object according this article.

all classes inherit from object:

Python class inherits object - Stack Overflow

Not sure what value is doing there. overwriting the __new__ method is not very common. value doesn’t seem to add anything (add any value haha), so not sure why you added this? Or is this an exercise? Or an external resource? Could you provide the source if this is the case?

Thanks for response, please take look at TestA class line 3 when I supercharge new it take only one argument (cls) and passes others arguments automatically
If I made the class like this:

class TestA:
	def __new__(cls, value):
		instance = super().__new__(cls, value)
		return instance
	def __init__(self, value):
		self.value = value
x = TestA(1) #TypeError: object.__new__() takes exactly one argument (the type to instantiate)

it throws error, why?

the __new__ method of parent class (object) only has one parameter.

the argument here:

x = TestA(1)

is passed along to the __init__ method. So init method should have a value parameter, the new method could be removed, given value has no purpose there. Once you remove the value parameter, the overwrite doesn’t contribute anything

overwriting the new method is something which is rarely done