Python Version = 3.9.6 IDE = vscode
Hi Folks, forgive me if i dont use the right terminology/nomenclature. Could really use your help with the following:
Im trying to subclass/extended/overload the built in "int" and "list" classes.
However, depending on how i define a integer variable with either direct assignment or int(), my extended method toString() will only work if i applied int().
The same happens with list(). It also depending on how the list object was created with [] or list() and only works with list().
Why DONT the variables 'b' and 'd' in my code below have access to the toString() methods ?
Thanks for your help in advance.
class int(int):
def __new__(cls, value): return super().__new__(cls, value)
def toString(self) -> str: return str(self)
c = int(8)
d = 8
print(c.toString())
print(d.toString()) # Error: 'int' object has no attribute 'toString'
class list(list):
def __init__(self, li): super(list, self).__init__(li)
def toString(self) -> str: return ' '.join(str(x) for x in self)
a = list([1,2,3])
b = [1,2,3]
print(a.toString())
print(b.toString()) # Error: 'list' object has no attribute 'toString'
The problem is that int and list are python types. When you say d=8, python makes it an int in the python built-ins. Making a int(8) however isn't overrided. Similar logic can be applied to your list object too.