0

I am trying to define Singleton class in python using a base class, following method 2 of this link, this is my code

class SingletonBase(object):

     def __new__(cls, slots=None):
        print(cls)
        if not hasattr(cls, 'instance'):
            print(object.__new__(cls))
            cls.instance = object.__new__(cls, slots=None)
            cls.instance.init_instance(slots=None)
        #else:
        return cls.instance


class Foo(SingletonBase):

    def init_instance(self, slots=None):
        self.slots = slots
        print(slots)

    def __init__(self):
        print('execute init.')

,when I run on my python terminal

Foo()

i'm getting this error

AttributeError: type object 'Foo' has no attribute 'instance'

Please help, how to resolve this. I tried defining instance = None at both SingletonBase and Foo class level, but nothing resolves.

  • I don't understand what exactly does cls.instance does? Does it try to access member variable of class template or class instance – Shubham Jain Nov 18 '19 at 02:15
  • Can't reproduce. Python 2.7.10 executes without error (but with a logic issue, see below); Python 3.7.5 complains about `slots` parameter to `object.__new__`. In no case am I getting the error you are. The logic error is, in the case you allocate the instance, you don't return it. If you change `object.__new__(cls, slots=None)` to `object.__new__(cls)`, delete `else:` and unindent `return cls.instance`. – Amadan Nov 18 '19 at 02:29
  • @Amadan are you using latest python version? – Shubham Jain Nov 18 '19 at 02:33
  • I said exactly which versions I was using. You did not though. Please make sure you have a [example]. – Amadan Nov 18 '19 at 02:36
  • I think that resolved, I should pass generalized arguments to __new__ method as ```(args, kwargs)``` and then pass it to init_instance. Thanks @Amadan. But yet did not understood the logic why passing explicitly ```slots=None``` returns AttributeError – Shubham Jain Nov 18 '19 at 03:03
  • I can't answer that question, since I can't reproduce it. As I said, passing `slots` to `object.__new__`, I am getting a `TypeError: object.__new__() takes exactly one argument (the type to instantiate)`, not an `AttributeError`. – Amadan Nov 18 '19 at 03:09

0 Answers0