4

I am trying to make a pattern singletone:

class Room:
    obj = None 

    def __new__(cls):          
        if cls.obj is None:               
            cls.obj = object.__new__(cls) 
        return cls.obj   

    def __init__(self, left_wall, right_wall, front_wall, back_wall):
        self.left_wall = left_wall
        self.right_wall = right_wall
        self.front_wall = front_wall
        self.back_wall = back_wall

    def __str__(self):
        return str(self.left_wall) + str(self.right_wall) + str(self.front_wall) + str(self.back_wall)


room_obj = Room(True, False, True, True)
print(room_obj)

room_obj2 = Room(True, False, False, True)
print(room_obj2)

print(room_obj is room_obj2)

After I run this code, in the console get the following:

kalinin@kalinin ~/python/object2 $ python index.py
TrueFalseTrueTrue
TrueFalseFalseTrue
False

It should not create two objects

stackow1
  • 261
  • 3
  • 10

1 Answers1

1

You can try this, this example in http://python-3-patterns-idioms-test.readthedocs.org/en/latest/Singleton.html

class OnlyOne:
    class __OnlyOne:
        def __init__(self, arg):
            self.val = arg
        def __str__(self):
            return repr(self) + self.val
    instance = None
    def __init__(self, arg):
        if not OnlyOne.instance:
            OnlyOne.instance = OnlyOne.__OnlyOne(arg)
        else:
            OnlyOne.instance.val = arg
    def __getattr__(self, name):
        return getattr(self.instance, name)
Nilesh
  • 17,950
  • 11
  • 74
  • 119