I am learning Python, and so far I understand the following about __new__ and __init__:

  1. __new__ is for object creation
  2. __init__ is for object initialization
  3. __new__ is invoked before __init__, as __new__ returns a new instance and __init__ is invoked afterwards to initialize inner state.
  4. __new__ is good for immutable objects, as they cannot be modified after creation. So, we can return a new instance with a new state.
  5. We can use __new__ and __init__ for mutable object as well since their inner state can be changed.

But I have other questions now.

  1. When I create a new instance such as a = MyClass("hello","world"), how are these arguments passed? I mean, how I should I structure the class using __init__ and __new__ since they both accept arbitrary arguments beyond the default first argument?
  2. Can the self keyword be changed to something else in name only? Similarly, can cls also be renamed, since it is just a parameter?

I made a little experiments as such below:

>>> class MyClass(tuple):
    def __new__(tuple):
        return [1,2,3]

and then:

>>> a = MyClass()
>>> a
[1, 2, 3]

Even through I said I want to return tuple, this code works fine and returned [1,2,3] (a list). I thought the first parameter to new should be the type of the instance we want to return. We're talking about the new function, right? I'm not familiar with how return types work in other languages in this context, beyond the concept of a bound type.

I also tried this:

>>> issubclass(MyClass,list)
Fa
Edit
Report