-2

I understand that when I do:

>>> int(4.0)
>>> int('10')

The __init__() method from the class of the argument (in the example, float and str, respectively), will be called.

I wonder what will happen if I do int(), I mean, without any argument. It wont call __int__() from class NoneType, because it doesn't implement that method.

What will happen?

Also, does this mean I can only directly call the constructor of class int if the argument is an int?

Thanks,

Tony Power
  • 1,033
  • 11
  • 23

1 Answers1

1

in python everything is an object, so when you call:

x = int(y) then constructor int.__new__(cls, value=y) is called.

this returns an int object and assigns it to x.

x may have a method bound to it: x.__init__() to control it's setup after creation, but creating the object in the first place is handled by the method __new__() of the base class.

If you provide no value to int(), the default value from the constructor call:

int.__new__(int, value=0) is substituted. Then as you mentioned, int has no __init__ method to modify it's setup after creation..

Community
  • 1
  • 1
Aaron
  • 10,133
  • 1
  • 24
  • 40