I want to shadow Python's int class, but I am having trouble with __init__.
The following code seems to work fine:
import builtins
class int(int):
"""Shadow Python builtin int class."""
def __init__(self, x, base=10, *, my_attr=False):
self.my_attr = my_attr
builtins.int.__init__(x, base)
But if I replace the line builtins.int.__init__(x, base) to either super().__init__(x, base)
or builtins.int.__init__(self, x, base) (which I think is the same as using super()), it doesn't work. I will get the following error:
a = int(5)
TypeError: object.__init__() takes exactly one argument (the instance to initialize)
I also tried super().__init__() (and builtins.int.__init__()) and they both would work as well. I am a bit confused because the int class in builtins.py is defined as (according to PyCharm):
def __init__(self, x, base=10): # known special case of int.__init__
which takes at least one argument x.
Can someone explain the inheritance in this case?
intis an immutable type. It is not initialised, only created via__new__.__init__does work. How come? If I use__new__, can I introduce new attributes likemy_attrin the code above?__init__all you want. It won't do anything. The second dupe works just fine too.a.my_attrand I can do integer operations likea - b(b = int(4)for example).