In terms of immutable classes, such as int__ new__ () does the definition of function stipulate that only 2 parameters can be accepted?

As shown in the figure, when inheriting the int class, override__ new__ () method. When extra parameters are added, an error will be reported

class test(int):
    def __new__(cls,a, b, c, d):
        return super().__new__(cls,a, b, c, d)

t = test(1,1,2,3)
    return super().__new__(cls,a, b, c, d)
TypeError: int() takes at most 2 arguments (4 given)

I know this is a call to int__ new__ (), except int__ new__ () it’s stipulated like this, otherwise it can’t convince me

When you call the superclass method, you are providing too many arguments.

If you called int(a, b, c, d) it would fail because int() does not accept four arguments. The same thing applies when you use super() to call the superclass method.

Write this instead:

class test(int):
    def __new__(cls,a, b, c, d):
        # I don't know what you want to do with c and d.
        return super().__new__(cls, a, b)

Now you can write test('ff', 16, 'this is ignored', 'so is this') and it will return 255.

1 Like

Why can’t I provide more parameters? Because int__ new__ Is it stipulated by itself or?

Let us have a look at some code:

>>> def adding(x, y):
...     return x + y
>>> adding(2,3)

Now if I do write:

>>> adding(2,3, 6)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    adding(2,3, 6)
TypeError: adding() takes 2 positional arguments but 3 were given

What else do you expect it to do with the 6? There is no formal parameter to equate it to, so the best thing to do is to return an error.

Whether the function is a builtin or something you write yourself, makes no difference . Here the possible formal parameters of int (and thus of int.__new__) are documented, you see there are at most 2. So if you pass in more, what is the function supposed to do with these? It can’t know, therefore the error.


You can’t provide more parameters to the int.__new__ because the int.__new__ method doesn’t accept more than two parameters.

What would it do with them?

Your subclass can accept as many parameters as you want. But you have to handle them in your __new__ method, you can’t pass them on to the superclass int, because it doesn’t know what to do with them and so will raise an exception.

You can’t do this:

result = int(1.5, 7, 'hello', 'goodbye')

for the exact same reason that you can’t do these either:

# Inside a class __new__ method.
return int.__new__(cls, 1.5, 7, 'hello', 'goodbye')
return super().__new__(cls, 1.5, 7, 'hello', 'goodbye')