I was trying to answer this question here with an inherited class solution, but when I tested it on my IDE my solution didn't came out as I expected. I did some search but couldn't find an answer.
Here was my proposed solution:
class PseudoInteger(int):
def __init__(self, x, base=10, hid_obj=""):
self.hidden_object = hid_obj
super(int, PseudoInteger).__init__(x, base)
pseudo_integer = PseudoInteger('5', hid_obj="Hello World")
print(5 + pseudo_integer) # Expects "10"
print(pseudo_integer == 5) # Expects "True"
print(pseudo_integer.hidden_object) # Expects "Hello World!"
To my understanding this should work in theory. But when I run it this is what I get:
pseudo_integer = PseudoInteger('5', hid_obj="Hello World") TypeError: 'hid_obj' is an invalid keyword argument for this function
I've tried adding base=10
when initiating the instance but it still fails:
pseudo_integer = PseudoInteger('5', base=10, hid_obj="Hello World") TypeError: int() takes at most 2 arguments (3 given)
I thought I had messed something up so I write my own class and inherit it, but it works fine:
class foo(object):
def __init__(self, x, y=10):
pass
class bar(foo):
def __init__(self, x, y=10, z=""):
self.z = z
super(foo, bar).__init__(x, y)
foobar = bar(1, z="hello")
print(foobar.z)
# Output
# hello
My question is - why couldn't I inherit the built-in int
class and add an additional argument, but it works fine when it's inherited from my foo
class? Is it a limitation or did I mess up?
In addition to @Melvin's suggestion of super() not needing args in Python 3, I tried it on my custom class, it works. But in the built-in inherited class I got another unexpected behaviour:
super().__init__(x, base) TypeError: object.__init__() takes no parameters
Built-ins are weird man.