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?

6
  • 2
    int is an immutable type. It is not initialised, only created via __new__. Commented Jan 4, 2021 at 19:03
  • 1
    Does this help: stackoverflow.com/q/3238350/2988730? Commented Jan 4, 2021 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? Commented Jan 4, 2021 at 19:19
  • @vanbastelaer. You can call __init__ all you want. It won't do anything. The second dupe works just fine too. Commented Jan 4, 2021 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). Commented Jan 4, 2021 at 19:26

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.