0

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?

vanbastelaer
  • 368
  • 2
  • 15
  • 2
    ``int`` is an immutable type. It is not initialised, only created via ``__new__``. – MisterMiyagi Jan 04 '21 at 19:03
  • 1
    Does this help: https://stackoverflow.com/q/3238350/2988730? – Mad Physicist Jan 04 '21 at 19:03
  • @MadPhysicist @MisterMiyagi But the code using `__init__` does work. How come? If I use `__new__`, can I introduce new attributes like `my_attr` in the code above? – vanbastelaer Jan 04 '21 at 19:19
  • @vanbastelaer. You can call `__init__` all you want. It won't do anything. The second dupe works just fine too. – Mad Physicist Jan 04 '21 at 19:24
  • @MadPhysicist But I was able to access `a.my_attr` and I can do integer operations like `a - b` (`b = int(4)` for example). – vanbastelaer Jan 04 '21 at 19:26
  • I'm not sure how that contradicts anything in the other answers. By subclassing, you introduce a `__dict__` attribute (which you could suppress by adding `__slots__`). – Mad Physicist Jan 04 '21 at 19:28

0 Answers0