0

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).

Harish Nair
  • 159
  • 4

1 Answers1

1

You want to implement something like Singleton. Most easier approach would be to overwrite __new__ instead of __init__.

hspandher
  • 15,934
  • 2
  • 32
  • 45