I've found similar questions but those are quite old (6-8 years old) and might be outdated, and by the way, some replies lack explanations.
I have written the following piece of python-3 code in order to make a class which supports storing names and unnamed fields the same way you can have variable named and unnamed parameters in a function call :
class struct(list):
def __init__(self, *args, **kwargs):
super().__init__(args)
for key, value in kwargs.items():
setattr(self, key, value)
def __repr__(self):
s = super().__repr__()[1:-1]
for key, val in self.__dict__.items():
s += ', '+key+'='+repr(val)
return 'struct('+s+')'
def __str__(self):
s = super().__str__()[1:-1]
print('Debug : super().__str__() = "'+super().__str__()+'"')
print('Debug : list(self).__str__() = "'+list(self).__str__()+'"')
print('Debug : s = "'+s+'"')
for key, val in self.__dict__.items():
s += ', '+key+'='+str(val)
return '{'+s+'}'
a = struct(1, 2, 3, a="akeja", b=21, c=True, d="lkj")
print('repr(a)="'+repr(a)+'"\n')
print('str(a)="'+str(a)+'"\n')
Executing this code in idle-3.5.2 will yield the following result :
>>>
RESTART: struct.py
repr(a)="struct(1, 2, 3, b=21, d='lkj', a='akeja', c=True)"
Debug : super().__str__() = "struct(1, 2, 3, b=21, d='lkj', a='akeja', c=True)"
Debug : list(self).__str__() = "[1, 2, 3]"
Debug : s = "truct(1, 2, 3, b=21, d='lkj', a='akeja', c=True"
str(a)="{truct(1, 2, 3, b=21, d='lkj', a='akeja', c=True, b=21, d=lkj, a=akeja, c=True}"
>>>
In this post, @Sven Marnach stressed out the need to use list.__init__(self, args)
instead of super().__init__(args)
in the __init__(...)
method, but that doesn't change anything (in reality, he wrote list.__init__(self, *args)
, but that one doesn't work at all).
However, as one can see in the second debug lines, the call to super().__str__()
which I expect to return the result from a call to the __str__
function from my super class (list
), will in fact return something which looks very much like the expected return from self.__repr__()
I can't figure out why self.__repr__()
seems to be called instead of list(self).__str__()
. Should I directly call __str__()
from list(self)
like in @Sven Marnach 6y.o. advice ? Is that the right way to do ? Why ? Or is this just a bug, which I should report ?