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. self
keyword is in terms of name can be changed to something else? But I am wonderingcls
is 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: