I was asked this question in an interview. What I tried to do was as follows:
class A:
l = []
def __init__(self):
if len(A.l)==0:
A.l.append(self)
else:
return A.l[0]
a = A()
b = A()
I came home and ran this code and understood that it won't work.
So I would like to know what is the correct way to solve this problem. The expected result is that when A()
is called for the second time, b
should point to the object that is already stored in a
(the first created object).