I am learning Python and so far I can tell the things below about __new__ and __init__:
- __new__is for object creation
- __init__is for object initialization
- __new__is invoked before- __init__as- __new__returns a new instance and- __init__invoked afterwards to initialize inner state.
- __new__is good for immutable object as they cannot be changed once they are assigned. So we can return new instance which has new state.
- We can use __new__and__init__for both mutable object as its inner state can be changed.
But I have another questions now.
- When I create a new instance such as a = MyClass("hello","world"), how these arguments are passed? I mean how I should structure the class using__init__and__new__as they are different and both accepts arbitrary arguments besides default first argument.
- selfkeyword is in terms of name can be changed to something else? But I am wondering- clsis in terms of name is subject to change to something else as it is just a parameter name?
I made a little experiments as such below:
>>> class MyClass(tuple):
    def __new__(tuple):
        return [1,2,3]
and I did below:
>>> a = MyClass()
>>> a
[1, 2, 3]
Albeit I said I want to return tuple, this code works fine and returned me [1,2,3]. I knew we were passing the first parameters as the type we wanted to receive once the __new__ function is invoked. We are talking about New function right? I don't know other languages return type other than bound type?
And I did anther things as well:
>>> issubclass(MyClass,list)
False
>>> issubclass(MyClass,tuple)
True
>>> isinstance(a,MyClass)
False
>>> isinstance(a,tuple)
False
>>> isinstance(a,list)
True
I didn't do more experiment because the further wasn't bright and I decided to stop there and decided to ask StackOverflow.
The SO posts I read:
 
     
     
     
    