0

I needed to create a singleton in for my code. So I followed these instructions, method 3.

Here is the code that I have:

class Singleton(type):
    _instances = {}
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]

def MyCfg(object):
    __metaclass__ = Singleton
    def __init__(self, p1 = 1, p2 = 2):
        # Some code

my_cfg = MyCfg()

However whenI run this code, I get a following error:

TypeError: MyCfg() takes exactly 1 argument (0 given)

I'm not new to python and programming but I never worked at with python at this level. I've been trying to understand what exactly happens in Singleton class but I can't figure out.

Would anyone be able to explain why this code generates an error?

Community
  • 1
  • 1
flashburn
  • 3,290
  • 3
  • 39
  • 76

1 Answers1

2

You have:

def MyCfg(object)

I am pretty sure you mean:

class MyCfg(object)

The error you are seeing (TypeError: MyCfg() takes exactly 1 argument (0 given)) is because with your current code, you are defining a function called MyCfg that takes a single argument (which you are not providing).

larsks
  • 194,279
  • 34
  • 297
  • 301