vendredi 8 mars 2019

Singleton class Instantiation: RecursionError: maximum recursion depth exceeded

I'am trying to implement Singleton class. This is my code:

class ImageUtils:
__instance = None
def __init__(self):  
   """ Virtually private constructor. """
   if ImageUtils.__instance != None:
     raise Exception("This class is a singleton!")
   else:
     ImageUtils.__instance = self          

@staticmethod
def getInstance():
    """Static access method"""
    if ImageUtils.getInstance() == None:
        ImageUtils()
    return ImageUtils.__instance

I test it like this:

s = ImageUtils()
print(s)

s = ImageUtils.getInstance()
print(s)

s = ImageUtils.getInstance()
print(s)

I get this error:

if ImageUtils.getInstance() == None: RecursionError: maximum recursion depth exceeded

Now, when I test the code here: Python Design Pattern Singletons, it gives me the expected result of printing the Singleton instance's memory location, three times.

Question: When I copy and paste the code given in the link, I get the expected result. However, the implementation of the ImageUtils class gives me RecursionError. Why is that? Any help is highly appreciated.

Aucun commentaire:

Enregistrer un commentaire