class B:
def __init__(self):
print('boo!')
self.a = []
def __repr__(self):
print(len(self.a))
ret = ''
for a in self.a:
ret += str(a)
return ret
The following is copy pasted from the Pycharm Console using python 3.8.6 and IPython 7.31.0:
>>> b = B()
boo!
0
0
>> b
Out[4]: 0
0
0
0
0
0
0
0
0
0
0
>> 2 + 3
Out[5]: 5
0
0
0
0
0
0
0
0
0
0
This does not happen in python REPL or iPython running in the cmd (see comments).
Why is this happening?
You're only showing and using
Bin your code, so we'll use just that.When you run just
B()(a call expression), this is the sequence of things that happens (in python and ipython):__new__(inherited fromobject)__init__, which printsboo!and sets theaattribute to an empty list[]__repr__, which in your case:0, the length ofaattributeretvariable to''aattribute which is empty''fromretHowever, step 3. applies only to running expressions
B(), the python interactive shell runs the expression and displays their result.The
b = B()assignment statement should not trigger a "display result" event (and will not in python, IDLE or ipython).