I've used Python for years without dabbling in the art of classes very much, and decided it's time to get some insight on the topic. I thus decided to play around with them a bit, and was in particular playing around with the dunder functionality. I made the following class:
class TestClass:
def __init__(self,y):
self.x = [1,2,3]
self.y = y
def __len__(self):
print('gottem')
return len(self.x)
def __str__(self):
print('gottem again')
return str(self.y)
Once I instantiate the class within the console, all subsequent console statements are concatenated with 'gottem', see console snippet below:
>>> 1+1
Out[2]: 2
>>> a = TestClass(3)
gottem
>>> 2+2
Out[4]: 4gottem
>>> len(a)
gottem
Out[5]: 3gottem
I've tried removing the __len__ definition, but I observe no similar behaviour with the __str__ definition, which indeed seems to function as I would expect. The behaviour goes away once I redefine a, so that the class instantiation is dropped. I am completely stumped as to what causes this behaviour, and why it only happens for __len__. Is there an obvious explanation behind this?
Info: I am running Anaconda's Python 3.7.6 distribution through Spyder.
Disclaimer: I absolutely tried to search for some information on this, but I either have no clue what to search for, or alternatively am doing something so fundamentally wrong that the questions don't even exist.